比方说,我有一个像这样的数据框:
Microsoft Windows [Version 10.0.18362.418]
(c) 2019 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>whoami
nt authority\system
C:\WINDOWS\system32>
我想要一个等于A [i-1]且等于B [i-1]的新列,所以:
A B
0 1 3
1 2 4
2 3 5
3 4 6
我该怎么做?
答案 0 :(得分:0)
IIUC,
一个想法是将列传递到列表并循环,同时为您的col分配shift()
cols = df.columns.tolist()
for col in cols:
df[f'{col}1'] = df[col].shift(1)
print(df)
A B A1 B1
0 1 3 NaN NaN
1 2 4 1.0 3.0
2 3 5 2.0 4.0
3 4 6 3.0 5.0