简体   繁体   中英

How to shift column values on a single dataframe row (Python Pandas)

The database I'm working with looks something like this:

         C1        C2         C3

R1      Nan       Nan         2

R2      1         Nan        Nan

R3      2         2          Nan

and I wanted to copy and shift that last value in each cell to the others in its row, and have something like this:

         C1        C2         C3

R1       2         2          2

R2      1          1          1

R3      2         2           2

How can I do it? I'm new with Pandas and I would like some help

You can try to ffill / bfill the rows:

out = df.ffill(axis=1).bfill(axis=1, downcast='infer')

output:

    C1  C2  C3
R1   2   2   2
R2   1   1   1
R3   2   2   2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM