注意 - 它不是 Converting/splitting and transposing a groupby or datetime object into dataframe 的重复项
我有一个 pandas df:
Reading
2016-06-01 09:00:00+09:00 1190.958
2016-06-01 10:30:00+09:00 1189.886
2016-06-01 12:00:00+09:00 1194.089
2016-06-01 13:30:00+09:00 1193.464
2016-06-01 15:00:00+09:00 1193.050
2016-06-02 09:00:00+09:00 1190.879
2016-06-02 12:00:00+09:00 1190.025
2016-06-02 13:30:00+09:00 1187.057
2016-06-02 15:00:00+09:00 1186.600
2016-06-03 09:00:00+09:00 1190.879
2016-06-03 10:30:00+09:00 1189.886
2016-06-03 12:00:00+09:00 1190.025
2016-06-03 13:30:00+09:00 1187.057
2016-06-03 15:00:00+09:00 1186.600
我想像这样转换它(作为示例)
09:00:00+09:00 10:30:00+09:00 12:00:00+09:00 13:30:00+09:00 15:00:00+09:00 09:00:00+09:00 10:30:00+09:00 12:00:00+09:00 13:30:00+09:00 15:00:00+09:00
2016-06-01 1190.958 1189.886 1194.089 1193.464 1193.050 1190.879 NA 1190.025 1187.057 1186.600
2016-06-02 1190.879 NA 1190.025 1187.057 1186.600 1190.958 1189.886 1194.089 1193.464 1193.050
所以对于每一天,我需要在每一天对应的行中获取前w天的数据(这里w=2)。
到目前为止我的方法是这样的: 使用建议的方法here我最初通过执行以下操作来获取每天的数据:
df.index = [df.index.date, df.index.time]
df= df.unstack()
然后我使用以下方法沿 axis=1 连接移动数据帧:
l=[df.shift(i) for i in np.arange(w)] # list of progressively shifted dataframes
df=pd.concat(l,axis=1) #all shifted dataframes concatenated along axis=1
有更好的方法吗?
最佳答案
遵循链接问题和答案的建议...这就是很好的问题回答:-)
df.index = [df.index.date, df.index.time]
d1 = df.Reading.unstack()
d1
然后使用 shift
和 pd.concat
定义一个新函数
def do_n_such_and_such(df, n):
k = len(df) - n + 1
shifts = [df.shift(s) for s in range(0, -n, -1)]
return pd.concat(shifts, axis=1).iloc[:k]
do_n_such_and_such(d1, 2)
关于python - 将多天的数据叠加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986875/