gpt4 book ai didi

numpy - Pandas:花式索引数据框

转载 作者:行者123 更新时间:2023-12-02 05:00:43 25 4
gpt4 key购买 nike

我有一个 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,它是具有匹配列的长达一年的每日时间序列(在同一时期内)。第二帧的值是 bool 值。

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),其中宽度是 bool 值暗示的不同列数 (width<=26)。

目前,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 有这种奇特的索引能力吗?我在文档中的任何地方都没有看到示例。

最佳答案

这是一种方法:

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)

关于numpy - Pandas:花式索引数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com