【问题标题】:MultiIndex Slicing with a Timeseries Row Index使用时间序列行索引的 MultiIndex 切片
【发布时间】:2015-10-14 03:53:46
【问题描述】:

我使用answer to this question 尝试在我的数据帧上制作类似的切片。但这似乎不起作用,因为我的行索引是 TimeSeries。我不知道如何改写切片才能工作。

我使用的 df 有一个 TimeSeries 索引,列是一个两级 MultiIndex。对于任意行,我试图返回一系列由每个主要列的“px”子列组成的。

第一次尝试:df.loc[0,(slice(None), 'px')] 抛出 TypeError,

TypeError: cannot do index indexing on <class 'pandas.tseries.index.DatetimeIndex'> with these indexers [0] of <type 'int'> 

所以我也尝试为它提供索引的 DateTime,而不是 int:

useIndex = sdf.index[0]
return df.loc[useIndex,(slice(None), 'px')]

这给出了一个:

KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)' 

后记...

如果我只是做一个简单的,

useIndex = sdf.index[0]
useIndex
sdf.iloc[useIndex]

我失败了:

TypeError: cannot do label indexing on <class 'pandas.tseries.index.DatetimeIndex'> with these indexers [2015-10-08 00:00:00] of <class 'pandas.tslib.Timestamp'>

所以问题可能是我并没有真正将有效索引传递给 MultiIndex 切片?

=================

这里有两个例子: 第一个 df ('df') 我能够提取出我想要的数据。第二个 df, ('df2') 引发类型错误。

import pandas as pd
import numpy as np

cols = [['col_1', 'col_2'], ['delta', 'px']]
multi_idx = pd.MultiIndex.from_product(cols, names= ["level_0", "level_1"])
df = pd.DataFrame(np.random.rand(20).reshape(5, 4), index=range(5), columns=multi_idx)

row_number =1 

print df.loc[df.index[row_number], pd.IndexSlice[:, 'px']]

rng = pd.date_range('1/1/2011', periods=5, freq='H')
df2 = pd.DataFrame(np.random.rand(20).reshape(5, 4), index=rng, columns=multi_idx)

#print df2.loc[df.index[row_number], pd.IndexSlice[:, 'px']]
useIndex = df2.index[0] 

print df2.loc[useIndex, pd.IndexSlice[:, 'px']]

【问题讨论】:

  • 您应该直接在此处复制/粘贴数据框,而不是将图像放入您的数据框。这会让其他人更容易复制数据框并使用 pd.read_clipboard() 来重现您的问题并进行测试。
  • 阿南德·S·库马尔。我已经“复制并粘贴”了数据帧的片段,但它最终在 stackoverflow 窗口中变成了乱码。
  • 复制粘贴后,应使用{}图标使其成为代码块,以免乱码
  • Anand S Kumar,你去吧,从我的终端复制,粘贴并标记为代码。
  • 你期望输出什么?

标签: python pandas


【解决方案1】:

使用IndexSlice 应该有助于获得您想要的结果。请注意,首先需要对列进行 lex 排序:

cols = [['col_1', 'col_2'], ['delta', 'px']]
multi_idx = pd.MultiIndex.from_product(cols, names= ["level_0", "level_1"])
df = pd.DataFrame(np.random.rand(20).reshape(5, 4), index=range(5), columns=multi_idx)

>>> df
level_0     col_1               col_2          
level_1     delta        px     delta        px
0        0.891758  0.071693  0.629897  0.693161
1        0.772542  0.022781  0.684584  0.892641
2        0.925957  0.794940  0.146950  0.134798
3        0.159558  0.842898  0.677927  0.028675
4        0.436268  0.989759  0.471879  0.101878

row_number = 3
>>> df.loc[df.index[row_number], pd.IndexSlice[:, 'px']]
level_0  level_1
col_1    px         0.842898
col_2    px         0.028675
Name: 3, dtype: float64

【讨论】:

  • 嗨。此处的示例有效,但问题是如果索引是 DateTime 索引,则 df.loc 返回类型错误 rng = pd.date_range('1/1/2011', period=5, freq='H') df2 = pd.DataFrame(np.random.rand(20).reshape(5, 4), index=rng, columns=multi_idx) print df2.loc[df.index[row_number], pd.IndexSlice[:, 'px' ]]
  • 在 Pandas 0.16.2 上为我工作。请注意您在评论中对 df 的不一致使用。应该是df2.loc[df2.index...
猜你喜欢
  • 2018-12-29
  • 2016-04-16
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 2014-12-17
  • 2019-08-04
  • 2021-12-07
相关资源
最近更新 更多