新的pandas数据帧来自另一个基于唯一多列索引的数据帧

2024-09-28 23:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创造一个新的熊猫.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

有什么想法吗?在


Tags: andin脚本dataframedfnewdbindex
1条回答
网友
1楼 · 发布于 2024-09-28 23:15:30

问题是您将new_df设置为索引列表,并删除了重复项:

new_df = df.index.drop_duplicates()

您需要的是只选择没有重复索引的行。您可以使用^{}函数筛选旧数据帧:

^{pr2}$

一个小例子,基于this

#create data sample with multi index
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'one', 'one', 'two', 'one', 'two', 'one', 'one']]
#(the first and last are duplicates)
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)

原始数据:

>>> s
first  second
bar    one      -0.932521
       one       1.969771
baz    one       1.574908
       two       0.125159
foo    one      -0.075174
       two       0.777039
qux    one      -0.992862
       one      -1.099260
dtype: float64

并过滤重复项:

>>> s[~s.index.duplicated()]
first  second
bar    one      -0.932521
baz    one       1.574908
       two       0.125159
foo    one      -0.075174
       two       0.777039
qux    one      -0.992862
dtype: float64

相关问题 更多 >