我有以下 df:
Mid South North
Elec Elec Elec
t
0 0 0 0
1 43102.490062 43102.490062 43102.490062
2 41692.002871 41692.002871 41692.002871
3 40592.822117 40592.822117 40592.822117
...
我想将其转换为以下 df:
Mid South North
Elec Elec Elec
t
0 43102.490062 43102.490062 43102.490062
1 41692.002871 41692.002871 41692.002871
2 40592.822117 40592.822117 40592.822117
...
所以基本上我需要将数据移到上面 1 行。
例如。如果我有索引 (0-3),我应该有索引 (0-2)
最佳答案
使用DataFrame.shift()
移动索引的方法:
import pandas as pd
# Recreate your example dataset
df = pd.DataFrame(data={'t': [0, 1, 2, 3], 'Mid Elec': [0., 43102.5, 41692.0, 40592.8], 'South Elec': [0., 43102.5, 41692.0, 40592.8], 'North Elec': [0., 43102.5, 41692.0, 40592.8]})
df.set_index('t', inplace=True)
df = df.shift(-1)
输出:
Mid Elec South Elec North Elec
t
0 43102.5 43102.5 43102.5
1 41692.0 41692.0 41692.0
2 40592.8 40592.8 40592.8
3 NaN NaN NaN
要删除最后一行,只需使用标准 Python 列表索引:
df = df[:-1]
输出:
Mid Elec South Elec North Elec
t
0 43102.5 43102.5 43102.5
1 41692.0 41692.0 41692.0
2 40592.8 40592.8 40592.8
关于python - 在 pandas Dataframe 中移动数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53855385/