python - 将多天的数据叠加在一起

标签 python pandas dataframe time-series

注意 - 它不是 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

enter image description here

然后使用 shiftpd.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)

enter image description here

关于python - 将多天的数据叠加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986875/

相关文章:

python - 句子分词器 - spaCy 到 pandas

Python范围: "UnboundLocalError: local variable ' c' referenced before assignment"

python - 在 python 中解析 HTML - lxml 或 BeautifulSoup?其中哪一个更适合什么样的目的?

python - 分块读取文件 - RAM 使用,从二进制文件中读取字符串

javascript - heroku python 和突出显示 js 不工作

python - Pandas DataFrame 构造函数对行进行排序,即使使用 OrderedDict 作为输入

python - Pandas - 选择列值出现 `n`次的行

python - 按参数列表过滤数据帧

python - to_csv() 写入带有附加分数的值

python - 字典到数据帧错误: "If using all scalar values, you must pass an index"