gpt4 book ai didi

python - 使用 Numpy datetime64 对象索引/切片 Pandas DataFrame

转载 作者:行者123 更新时间:2023-12-01 01:30:54 25 4
gpt4 key购买 nike

我想知道是否可以让以下内容工作(Pandas 0.23.4)。任何帮助将不胜感激。

import numpy as np
import pandas as pd

rows = 12
rng = pd.date_range('2011-01', periods=rows, freq='M')

df = pd.DataFrame(np.arange(rows), index=rng)

print(df.loc['2011-01'])
print(df.loc[np.datetime64('2011-01')])

第一个 print 执行了我所期望的操作:显示 2011 年 1 月的所有行。但是,第二个会抛出 KeyError 因为该值不是在索引中。我希望它能提供相同的输出,但经过一些测试后,我意识到它正在寻找完全匹配的 2011-01-01,而该匹配不在 DataFrame 中。我希望第二个能够工作,这样我就可以使用 numpy.arange 或 pandas.date_range 轻松生成可以循环的日期数组。有人让这个工作吗?(看起来像 this works ,但前提是您的日期完全匹配。)

最佳答案

使用DatetimeIndex.to_period() & Period.month

import numpy as np
import pandas as pd

rows = 12
rng = pd.date_range('2011-01', periods=rows, freq='M')

df = pd.DataFrame(np.arange(rows), index=rng)

# print(df.loc['2011-01'])
for idx, di in enumerate(df.index.to_period()):
if di.month == np.datetime64('2011-01').item().month:
print(f'loc: [{idx}] == {df.index[idx]}')

输出:

# loc: [0] == 2011-01-31 00:00:00

由于您的 df 索引由月末日期组成,因此您可以使用此技巧来使用 df.loc 来获取行:

>>>> df.loc[df.index == np.datetime64('2011-03', 'D') -1]
0
2011-02-28 1

>>>> df.loc[df.index == np.datetime64('2011-04', 'D') -1]
0
2011-03-31 2

>>>> df[df.index == np.datetime64('2011-12', 'D') -1]
0
2011-11-30 10

# use 2012 January 1st minus one day to get 2011 Dec 31st
>>>> df[df.index == np.datetime64('2012-01', 'D') -1]
0
2011-12-31 11

关于python - 使用 Numpy datetime64 对象索引/切片 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52883494/

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