Search code examples
pythonpython-3.xpandastransformreindex

Transforming data frame in python


I have a situation where I have the following dataset:

ID      A     B    C
1      aa     -    -
2      -      bb   -
3      -      -    cc
4      aaa    -    -

that should be transformed to the following data frame:

ID    A
 1    aa
 2    bb
 3    cc
 4    aa

So essentially shifting rows so that it fits to the first column


Solution

  • you can use bfill with axis along columns after replace the symbol '-' by nan:

    df_ = df.replace('-', np.nan).bfill(1)[['ID', 'A']]
    print(df_)
      ID    A
    0  1   aa
    1  2   bb
    2  3   cc
    3  4  aaa