我有一个包含数千行的 DataFrame,我需要将 column A
中的所有项目向上偏移 1 行以获得类似于 column B
中的值。我可以松开第 0 行的项目,然后用上一行的项目填充最后一行。我只是不知道如何剪切和粘贴所有内容 1。
A B
0 0 0
1 0 1
2 1 1
3 1 1
4 1 1
5 1 2
6 2 2
7 2 2
8 2 3
9 3 3
10 3 4
11 4 4
12 4 4
13 4 4
最佳答案
IIUC ffill
和 shift
df['A'] = df['A'].shift(-1).ffill()
print(df)
A B
0 0.0 0
1 1.0 1
2 1.0 1
3 1.0 1
4 1.0 1
5 2.0 2
6 2.0 2
7 2.0 2
8 3.0 3
9 3.0 3
10 4.0 4
11 4.0 4
12 4.0 4
13 4.0 4
关于python - pandas DataFrame 偏移列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58440807/