我有一个以下格式的数据框:
timestamp,name,age
2020-03-01 00:00:01,nick
2020-03-01 00:00:01,john
2020-03-01 00:00:02,nick
2020-03-01 00:00:02,john
2020-03-01 00:00:04,peter
2020-03-01 00:00:05,john
2020-03-01 00:00:10,nick
2020-03-01 00:00:12,john
2020-03-01 00:00:54,hank
2020-03-01 00:01:03,peter
我正在尝试根据时间间隔(例如1分钟)将此数据帧拆分为多个数据帧,并将结果附加到字典中。
我正在尝试:
df = pd.read_csv('/home/antonis/repos/newtest.csv')
minutesplit = {n: g.reset_index()
for n, g in df.set_index('timestamp').groupby(pd.Grouper(key='timestamp',freq='1Min'))}
但发生错误,例如:
KeyError:'找不到石斑鱼名字时间戳'
有人知道我在做什么错吗?
答案 0 :(得分:0)
首先通过参数timestamp
将列parse_dates
转换为日期时间:
df = pd.read_csv('/home/antonis/repos/newtest.csv', parse_dates=['timestamp'])
然后不必将set_index
转换为索引,而将reset_index
的索引转换为列,则Grouper
使用参数key
来查找列{{1} }:
以下是日期时间创建的DataFrames词典中的键,因此使用timestamp
进行填充:
pd.Timestamp
如果使用键将其转换为字符串minutesplit = {n: g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))}
print (minutesplit[pd.Timestamp('2020-03-01 00:01')])
timestamp name age
9 2020-03-01 00:01:03 peter NaN
YYYY-MM-DD HH:MM
:
strftime
如果需要minutesplit = {n.strftime('%Y-%m-%d %H:%M'): g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='1Min'))}
print (minutesplit['2020-03-01 00:01'])
timestamp name age
9 2020-03-01 00:01:03 peter NaN
的列表:
DataFrame