Home>

I have been studying python for about a month.

df = pd.DataFrame ([[1,2,3], [4,5,6], [7,8,9]])


For example, in the above data frame, when the 0th column is'4&apos ;, I want to return a data frame with the row shifted to the right. I want to do as follows. Thank you.

df = pd.DataFrame ([[1,2,3], [nan, 4,5], [7,8,9]])
Error message
Error message
Applicable source code
Source code
Tried
df [df.iloc [:, 0] == 4] .shift (1, axis = 1)
Supplemental information (FW/tool version etc.)

Please provide more detailed information here.

  • Answer # 1

    shiftSet the result to the originaldf.

    mask = df.iloc [:, 0] == 4
    df.loc [mask] = df.loc [mask] .shift (axis = 1)

    or use themaskmethod.

    df.mask (df.iloc [:, 0] == 4, df.shift (axis = 1), inplace = True)

    If you don't want to change the originaldf, in the first example you need to createdf.copy ()before replacing it. In the second example, useinplace = Falseand use the return value.