如何根据日期组织数据帧并为列分配新值



我有一个不包括星期六和星期日的月份数据帧,每 1 分钟记录一次。

v1         v2  
2017-04-03 09:15:00     35.7       35.4  
2017-04-03 09:16:00     28.7       28.5
...               ...        ...
2017-04-03 16:29:00     81.7       81.5
2017-04-03 16:30:00     82.7       82.6
...               ...        ...
2017-04-04 09:15:00     24.3       24.2  
2017-04-04 09:16:00     25.6       25.5
...               ...        ...
2017-04-04 16:29:00     67.0       67.2
2017-04-04 16:30:00     70.2       70.6
...               ...        ...
2017-04-28 09:15:00     31.7       31.4  
2017-04-28 09:16:00     31.5       31.0
...               ...        ...
2017-04-28 16:29:00     33.2       33.5
2017-04-28 16:30:00     33.0       30.7

我重新采样了数据帧以获取每天的第一个也是最后一个值。

res = df.groupby(df.index.date).apply(lambda x: x.iloc[[0, -1]])
res.index = res.index.droplevel(0)
print(res)
v1    v2
2017-04-03 09:15:00  35.7  35.4
2017-04-03 16:30:00  82.7  82.6
2017-04-04 09:15:00  24.3  24.2
2017-04-04 16:30:00  70.2  70.6
...                ..    ..
2017-04-28 09:15:00  31.7  31.4
2017-04-28 16:30:00  33.0  30.7

现在我想将数据框组织为日期,其中 v1 为最小时间戳,v2 为特定日期的最大时间戳。

期望输出:

v1    v2
2017-04-03  35.7  82.6
2017-04-04  24.3  70.6
...       ..    ..
2017-04-28  31.7  30.7

您可以在索引上按 groupby 并将groupby.agg与自定义函数一起使用。

df1 = res.groupby(res.index.date).agg({'v1': lambda x: x[min(x.index)], 'v2':lambda x: x[max(x.index)]})
print (df1)
v1      v2
2017-04-03  35.7    82.6
2017-04-04  24.3    70.6
2017-04-28  31.7    33.7

重新采样数据帧以获取每天的第一个也是最后一个值的替代方法。

res=df.reset_index().groupby(df.index.date).agg(['first','last']).stack().set_index('index')
Out[123]:
v1     v2
index       
2017-04-03 09:15:00  35.7   35.4
2017-04-03 16:30:00  82.7   82.6
2017-04-04 09:15:00  24.3   24.2
2017-04-04 16:30:00  70.2   70.6
2017-04-28 09:15:00  31.7   31.4
2017-04-28 16:30:00  33.0   33.7

试试这个:

df_result = pd.DataFrame()
df_result['v1'] = res.groupby(res.index)['v1'].min()
df_result['v2'] = res.groupby(res.index)['v2'].max()

在熊猫中有一个非常有趣的爱好来处理日期时间索引。 这是重采样功能。 在您的情况下,请尝试以下操作:

def first_last(entry):
return entry['v1'][0],entry['v2'][1]
yourdataframe.resample('D').apply(first_last)

"D"代表每日重采样。

结果:

Dates                 
2017-04-03  35.7  82.6
2017-04-04  24.3  70.6

您可以使用自定义函数reset_index然后GroupBy+apply

def first_second(x):
return pd.Series({'v1': x['v1'].iat[0], 'v2': x['v2'].iat[-1]})
res2 = res.reset_index()
res2 = res2.groupby(res2['index'].dt.date).apply(first_second)
print(res2)
v1    v2
index                 
2017-04-03  35.7  82.6
2017-04-04  24.3  70.6
2017-04-28  31.7  33.7

最新更新