我的数据框如下,我想重新排列、更新并将其保存为 csv 或类似格式。
time lat lon ws wd
1/1/2023 0:00 -5 107 8.214895 313.9049
1/1/2023 0:00 -5 107.25 8.351197 314.44873
1/1/2023 0:00 -5.25 107 7.6247864 307.61456
1/1/2023 1:00 -5 107 8.084728 310.0435
1/1/2023 1:00 -5 107.25 8.091071 308.73547
1/1/2023 1:00 -5.25 107 7.4219675 302.27475
1/1/2023 2:00 -5 107.25 7.8656287 304.08533
1/1/2023 2:00 -5 107.5 8.087259 300.91684
1/1/2023 2:00 -5.25 107 7.4953856 300.94644
所需的df:
time ws wd ws wd ws wd
0 8.214895 313.9049 8.351197 314.44873 7.6247864 307.61456
3600 8.084728 310.0435 8.091071 308.73547 7.4219675 302.27475
7200 7.8656287 304.08533 8.087259 300.91684 7.4953856 300.94644
将每个时间步的所有 ws wd 分组在一行中。一个时间步长为 1 小时(3600 秒),一天 24 行,第二天为 25 小时、26 小时(90000 秒、93600 秒等)。
我尝试过 stack、unstack、pivot,但可能遗漏了一些东西。 我将不胜感激你的建议。谢谢你。
用途:
times = pd.to_datetime(df['time'])
df['time'] = times.sub(times[0]).dt.total_seconds().astype(int)
out = (df.assign(g = df.groupby('time').cumcount())
.pivot(index='time', values=['ws','wd'], columns='g')
.sort_index(level=[1, 0], axis=1, ascending=[True, False]))
out.columns = out.columns.map(lambda x: f'{x[0]}_{x[1]}')
print (out)
ws_0 wd_0 ws_1 wd_1 ws_2 wd_2
time
0 8.214895 313.90490 8.351197 314.44873 7.624786 307.61456
3600 8.084728 310.04350 8.091071 308.73547 7.421968 302.27475
7200 7.865629 304.08533 8.087259 300.91684 7.495386 300.94644