python - 在 pandas Dataframe 中移动数据

标签 python pandas row

我有以下 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/

相关文章:

python - 如何在 pandas 数据框切片中插入一系列值

html - css 在小窗口宽度下更改表中元素的顺序

python - Pandas 删除每行中部分完成数据的重复项并合并数据

python - 来自具有空列表值的字典的 Pandas Dataframe

python - 为什么 cv2.imread() 不存储我的图像文件的名称?

python - 在 Python 中使用 Pandas 进行特征工程,每次计算使用多行

matlab - 根据特定列的值提取多列

Python 列表推导式、子列表行和列

python - Django vs Grails vs Lift支持Comet吗?

python - Django 中如何拥有一个地址字段?