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.

2
  • same question here : stackoverflow.com/questions/32062157/… Commented Jan 3, 2019 at 13:26
  • Thanks, there I found one working solution. Commented Jan 3, 2019 at 13:58

1 Answer 1

1

You can just use the built in fillna

df.fillna(method='bfill', axis=1)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but it doesn't work. Perhaps because the content of the cells is " " which seems to be different from nan.
you can replace all instances of “” with np.nan which should then allow this to work
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.