我想创造一个新的熊猫.DataFrame从另一个熊猫.DataFrame基于唯一的多列索引。我能创造一个熊猫.核心.索引.MultiIndex使用df.index.drop\u重复项(),但我不知道如何将其转换为熊猫.DataFrame. 在
以下脚本使用SQL查询创建原始数据帧。在
import sqlite3 as db
import pandas as pd
conn = db.connect('C:/data.db')
query = """SELECT TimeStamp, UnderlyingSymbol, Expiry, Strike, CP, BisectIV, OTMperc FROM ActiveOptions
WHERE TimeStamp = '2015-11-09 16:00:00' AND UnderlyingSymbol = 'INTC' AND
Expiry < '2015-11-27 16:00:00' AND OTMperc < .02 AND OTMperc > -.02
ORDER BY UnderlyingSymbol, Expiry, ABS(OTMperc)"""
df = pd.read_sql_query(sql=query, con=conn,index_col=['TimeStamp', 'UnderlyingSymbol', 'Expiry'],
parse_dates=['TimeStamp', 'Expiry'])
脚本将创建以下数据帧:
^{pr2}$创建具有唯一多列索引的新DataFrame将生成以下输出:
In[10]: new_df = df.index.drop_duplicates()
In[11]: new_df
Out[11]:
MultiIndex(levels=[[2015-11-09 16:00:00], [u'INTC'], [2015-11-13 16:00:00, 2015-11-20 16:00:00]],
labels=[[0, 0], [0, 0], [0, 1]],
names=[u'TimeStamp', u'UnderlyingSymbol', u'Expiry'])
In[12]: type(new_df)
Out[12]: pandas.core.index.MultiIndex
有什么想法吗?在
问题是您将
new_df
设置为索引列表,并删除了重复项:您需要的是只选择没有重复索引的行。您可以使用^{} 函数筛选旧数据帧:
^{pr2}$一个小例子,基于this:
原始数据:
并过滤重复项:
相关问题 更多 >
编程相关推荐