0

I have the following problem. I have to shift the values in the dataframe (python) to the left, if some cells are empty. So, if I have a dataframe

  col1 col2 col3 col4
0    A         B    D
1    C    E    E    A
2    E    A    E    A
3    A         D    D
4    B    B    B    B
5    D         A    D
6    F    F         F
7    E    E    E    E
8    B    B    B    B

I would like to obtain the dataframe

  col1 col2 col3 col4
0    A    B    D
1    C    E    E    A
2    E    A    E    A
3    A    D    D
4    B    B    B    B
5    D    A    D
6    F    F    F
7    E    E    E    E
8    B    B    B    B

Actually I have much more columns than only 4, therefore I hope to find a solution which doesn't depend on the exact number of columns. If anybode can give me a link where the similar operations on dataframes are explained, it would be also nice. As for now, I don't really understand how python dataframes are organised (I come from the SAS world and python is pretty new for me). Thank You in advance.

EDIT: the suggested solution with the justify function from "Python: Justifying NumPy array" only works if the cells contain only one symbol.

Denis
  • 99
  • 10

1 Answers1

1

You can just use the built in fillna

df.fillna(method='bfill', axis=1)
gold_cy
  • 13,648
  • 3
  • 23
  • 45
  • Thanks but it doesn't work. Perhaps because the content of the cells is " " which seems to be different from nan. – Denis Jan 03 '19 at 13:36
  • you can replace all instances of “” with np.nan which should then allow this to work – gold_cy Jan 03 '19 at 13:38
  • Yes, now it works but only partially. It doesn't shift the cells, it replaces the empty cell with the content of the right cell. But the right cell isn't empty after that. This is not what I am looking for. – Denis Jan 03 '19 at 13:51