gpt4 book ai didi

python - 对 Pandas DataFrame 进行切片以显示特定日期的所有记录

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:06 25 4
gpt4 key购买 nike

我想返回一个数据帧,其中仅包含给定日期时间值的特定日期的记录。

下面的代码正在运行:

def dataframeByDay(datetimeValue):
cYear = datetimeValue.year
cMonth = datetimeValue.month
cDay = datetimeValue.day
crit = (df.index.year == cYear) & (df.index.month == cMonth) & (df.index.day == cDay)
return df.loc[crit]

是否有更好(更快)的方法来完成此任务?

最佳答案

由于索引是 DatetimeIndex,因此您可以使用字符串对其进行切片。

考虑数据帧df

np.random.seed([3,1415])
df = pd.DataFrame(np.random.randint(10, size=(10, 3)),
pd.date_range('2016-03-31', periods=10, freq='12H'),
list('ABC'))

df

A B C
2016-03-31 00:00:00 0 2 7
2016-03-31 12:00:00 3 8 7
2016-04-01 00:00:00 0 6 8
2016-04-01 12:00:00 6 0 2
2016-04-02 00:00:00 0 4 9
2016-04-02 12:00:00 7 3 2
2016-04-03 00:00:00 4 3 3
2016-04-03 12:00:00 6 7 7
2016-04-04 00:00:00 4 5 3
2016-04-04 12:00:00 7 5 9

不是你想要的
您不想使用时间戳

df.loc[pd.to_datetime('2016-04-01')]

A 0
B 6
C 8
Name: 2016-04-01 00:00:00, dtype: int64

相反
您可以使用此技术:

df.loc['{:%Y-%m-%d}'.format(pd.to_datetime('2016-04-01'))]

A B C
2016-04-01 00:00:00 7 3 1
2016-04-01 12:00:00 0 6 6

你的函数

def dataframeByDay(datetimeValue):
return df.loc['{:%Y-%m-%d}'.format(datetimeValue)]

dataframeByDay(pd.to_datetime('2016-04-01'))

A B C
2016-04-01 00:00:00 7 3 1
2016-04-01 12:00:00 0 6 6
<小时/>

这里有一些替代方法

def dataframeByDay2(datetimeValue):
dtype = 'datetime64[D]'
d = np.array('{:%Y-%m-%d}'.format(datetimeValue), dtype)
return df[df.index.values.astype(dtype) == d]

def dataframeByDay3(datetimeValue):
return df[df.index.floor('D') == datetimeValue.floor('D')]

关于python - 对 Pandas DataFrame 进行切片以显示特定日期的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208431/

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