我是从一个Excel文件中读取的,该文件有一个具有时间的列。因为我无法上传实际文件,所以我创建了变量timeIntervals
来说明。
当我运行这个代码时..。
import pandas as pd
import datetime
from pyPython import *
def main():
timeIntervals = pd.date_range("11:00", "21:30", freq="30min").time
df = pd.DataFrame({"Times": timeIntervals})
grp = pd.Grouper(key="Times", freq="3H")
value = df.groupby(grp).count()
print(value)
if __name__ == '__main__':
main()
我得到以下错误:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
如何结合使用pandas.Grouper
和DataFrame.groupby
将数据df
“分组”成离散时间范围(3小时)?还有其他选择吗?
发布于 2021-10-26 23:52:43
以下几个问题:
window.
count
计算列中的非NaN值,因此必须提供非NaN值,因为示例帧中没有剩余的列。我们可以通过将time列转换为datetime来解决第一个问题:
timeIntervals = pd.date_range("11:00", "21:30", freq="30min") # remove time here
df = pd.DataFrame({"Times": timeIntervals})
如果我们不是从date_range
中创建这些值,我们可以简单地转换列to_datetime
df['Times'] = pd.to_datetime(df['Times'], format='%H:%M:%S')
然后我们就可以分组计算:
value = df.groupby(pd.Grouper(key="Times", freq="3H"))['Times'].count()
如果需要,我们可以更新index
以只反映分组后的time
:
value.index = value.index.time
因此,value
变成了:
09:00:00 2
12:00:00 6
15:00:00 6
18:00:00 6
21:00:00 2
Name: Times, dtype: int64
和to_datetime
一起
def main():
time_intervals = pd.date_range("11:00", "21:30", freq="30min").time
df = pd.DataFrame({"Times": time_intervals})
# Convert to DateTime
df['Times'] = pd.to_datetime(df['Times'], format='%H:%M:%S')
# Group and count specific column
value = df.groupby(pd.Grouper(key="Times", freq="3H"))['Times'].count()
# Retrieve only Time information
value.index = value.index.time
print(value)
或者在创建time
之前不检索DataFrame:
def main():
time_intervals = pd.date_range("11:00", "21:30", freq="30min")
df = pd.DataFrame({"Times": time_intervals})
value = df.groupby(pd.Grouper(key="Times", freq="3H"))['Times'].count()
value.index = value.index.time
print(value)
https://stackoverflow.com/questions/69731081
复制相似问题