[英]Python pandas: Multicolumn dataframe - Shift one column without changing the other
Supposing I have the following dataframe: 假设我有以下数据框:
df =
Index Col1 Col2 Col3 Col4
0 10 20 30 40
1 11 21 31 41
2 12 22 32 42
3 13 23 33 43
Is there a pandas function or a simple way (without creating a duplicate .copy() dataframe) that will allow me to return the same dataframe but with one or more columns (eg Col2 & Col3) shifted by one row ie .shift(1) without overwriting it? 是否有熊猫函数或简单方法(无需创建重复的.copy()数据框)使我可以返回相同的数据框,但将一列或多列(例如Col2和Col3)移位了一行,即.shift(1 )而不覆盖它?
In other words to get the following 换句话说获得以下
df =
Index Col1 Col2 Col3 Col4
0 10 nan nan 40
1 11 20 30 41
2 12 21 31 42
3 13 22 32 43
Select columns by subset and apply function shift
: 按子集选择列并应用
shift
功能:
cols = ['Col2','Col3']
df[cols] = df[cols].shift(1)
print (df)
Col1 Col2 Col3 Col4
Index
0 10 NaN NaN 40
1 11 20.0 30.0 41
2 12 21.0 31.0 42
3 13 22.0 32.0 43
EDIT: 编辑:
cols = ['Col2','Col3']
another_cols = df.columns.difference(cols)
df1 = df[another_cols].combine_first(df[cols].shift(1))
print (df1)
Col1 Col2 Col3 Col4
Index
0 10 NaN NaN 40
1 11 20.0 30.0 41
2 12 21.0 31.0 42
3 13 22.0 32.0 43
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.