【问题标题】:Pandas: fancy indexing a dataframePandas:花式索引数据框
【发布时间】:2013-05-09 22:28:43
【问题描述】:

我有一个 Pandas 数据框 df1,它是一个长达一年的 5 分钟 时间序列,包含 A-Z 列。

df1.shape
(105121, 26)
df1.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2002-01-02 00:00:00, ..., 2003-01-02 00:00:00]
Length: 105121, Freq: 5T, Timezone: None

我有第二个数据框 df2,它是一个长达一年的每天时间序列(在同一时期内),具有匹配的列。第二帧的值是布尔值。

df2.shape
(365, 26)
df2.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2002-01-02 00:00:00, ..., 2003-01-01 00:00:00]
Length: 365, Freq: D, Timezone: None

我想将 df2 用作 df1 的精美索引,即“df1.ix[df2]”或类似的东西,这样我就可以为每个日期返回 df1 列的子集——即 df2 表示为 True 的那些那个日期(上面有所有的时间戳)。因此,结果的形状应该是 (105121, width),其中 width 是布尔值所暗示的不同列的数量 (width

目前,df1.ix[df2] 仅部分有效。只挑选出每天 00:00 的值,根据 df2 的“点状”时间序列,这很有意义。

我接下来尝试将时间跨度作为 df2 索引:

df2.index
PeriodIndex: 365 entries, 2002-01-02 to 2003-01-01

这一次,我得到一个错误:

/home/wchapman/.local/lib/python2.7/site-packages/pandas-0.11.0-py2.7-linux-x86_64.egg/pandas/core/index.pyc in get_indexer(self, target, method, limit)
    844             this = self.astype(object)
    845             target = target.astype(object)
--> 846             return this.get_indexer(target, method=method, limit=limit)
    847 
    848         if not self.is_unique:

AttributeError: 'numpy.ndarray' object has no attribute 'get_indexer'

我的临时解决方案是按日期循环,但这似乎效率低下。 Pandas 有能力进行这种花哨的索引吗?我在文档中的任何地方都没有看到示例。

【问题讨论】:

  • 您可以将df2 重新采样到 5 分钟并填充它。
  • 谢谢——应该提到我也试过了。得到 ValueError:无法使用多维键进行索引。

标签: numpy pandas


【解决方案1】:

这是一种方法:

t_index = df1.index
d_index = df2.index
mask = t_index.map(lambda t: t.date() in d_index)
df1[mask]

稍微快一点(但想法相同)将是使用:

mask = pd.to_datetime([datetime.date(*t_tuple)
                           for t_tuple in zip(t_index.year,
                                              t_index.month,
                                              t_index.day)]).isin(d_index)

【讨论】:

  • .date 可能是 DatetimeIndex 的一种有用方法(我想我会把它放在一起)。
  • 谢谢安迪,但我的问题有点复杂。我需要使用 df2 的(布尔),而不是索引,作为 df1 的精美索引,如下所示(numpy): a = np.arange(5) b = np. asarray([True. False, True, False, True]) a[b] ---> array([0, 2, 4])。碰巧的是,上面的代码拉回了整个 df1,因为 df1 的日期时间都在 df2 的日期之内。我需要的是返回 df1 的正确 columns ——即在相应的 df2 列中由 True 值标识的那些。而且这个选择会因天而异。
猜你喜欢
  • 2020-10-22
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多