gpt4 book ai didi

python - Pb 在时间序列索引上进行行选择

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:50 26 4
gpt4 key购买 nike

有了这个玩具数据::

df = pd.DataFrame(pd.np.random.randint(2, 9, size=(8, 3)))
df.index = pd.date_range(start='2015-04', periods=8, freq='Q')
df
# 0 1 2
# 2015-06-30 7 5 5
# 2015-09-30 5 5 8
# 2015-12-31 2 4 3
# 2016-03-31 2 5 8
# 2016-06-30 2 2 3
# 2016-09-30 6 6 6
# 2016-12-31 8 5 3
# 2017-03-31 8 2 2

这很好用,我们可以过滤特定月份::

df.loc[df.index.month == 9, :]
# 0 1 2
# 2015-09-30 5 5 8
# 2016-09-30 6 6 6

但是如果我们需要从列表中获取值,如何制作“isin”过滤器呢?::

df.loc[df.index.month in [6, 12], :]
# ---------------------------------------------------------------------------
# ValueError Traceback (most recent call last)
# <ipython-input-577-49bc5540b6dd> in <module>()
# ----> 1 df.loc[df.index.month in [6, 12], :]
#
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

最佳答案

您可以使用np.in1d()测试一维数组的每个元素是否也存在于第二个数组中。

In [32]: df.loc[np.in1d(df.index.month, [6, 12]), :]
Out[32]:
0 1 2
2015-06-30 8 6 4
2015-12-31 2 3 4
2016-06-30 8 7 3
2016-12-31 4 7 3

但是,如果您只想使用“isin()”方法,则可以将 df.index.month 转换为系列并检查 isin([6, 12]) 条件

In [34]: df.loc[pd.Series(df.index.month).isin([6, 12]).values, :]
Out[34]:
0 1 2
2015-06-30 8 6 4
2015-12-31 2 3 4
2016-06-30 8 7 3
2016-12-31 4 7 3

或者,您也可以

In [33]: df.loc[[x in [6, 12] for x in df.index.month], :]
Out[33]:
0 1 2
2015-06-30 8 6 4
2015-12-31 2 3 4
2016-06-30 8 7 3
2016-12-31 4 7 3

关于python - Pb 在时间序列索引上进行行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30578303/

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