根据熊猫其他列中的值移动列

时间:2020-03-06 09:23:53

标签: pandas dataframe conditional-statements shift

我有一个dataframe,如下所示:

id  FY   SY   TY   Ylen
1   2018 2019 nan  2
2   2017 2018 2019 3
3   2018 2019 2020 3
4   2019 nan  nan  1
5   2018 nan  nan  1

我想根据Ylen中显示的数字移动列,使其看起来像这样:

id  FY   SY   TY   Ylen
1   nan  2018 2019 2
2   2017 2018 2019 3
3   2018 2019 2020 3
4   nan  nan  2019 1
5   nan  nan  2018 1

是否有条件shift()

1 个答案:

答案 0 :(得分:1)

首先是必需的相同类型的数据,这里是float s,然后是DataFrame.shift列,按条件:

c = ['FY','SY','TY']

df[c] = df[c].astype(float)

for s in df['Ylen'].unique():
    m = df['Ylen'].eq(s)
    df.loc[m, c] = df.loc[m, c].shift(len(c)-s, axis=1)
print (df)
   id      FY      SY      TY  Ylen
0   1     NaN  2018.0  2019.0     2
1   2  2017.0  2018.0  2019.0     3
2   3  2018.0  2019.0  2020.0     3
3   4     NaN     NaN  2019.0     1
4   5     NaN     NaN  2018.0     1