1

I have a dataframe that looks like this:

  Z1  Z2  Z3 Z4
   0   0   A  A
   0   B   0  0
   C   0   C  0
   D   0   D  0
   0   0   E  0 

I want to remove the cells with the value 0 and make it to look like this:

  Z1  Z2  Z3 Z4
  C   B   A  A
  D       C  
          D  
          E  
4
  • 1
    what do you want to replace the zeros with? NaNs? ""? Commented Feb 13, 2018 at 13:49
  • No I dont want them at all in the dataframe I want to move up "C" and "D" in column Z1 Commented Feb 13, 2018 at 13:49
  • You can't remove cells from a dataframe. If a row is present, there must be a value for each column of the dataframe in that row. Can you describe better what you're trying to do? Commented Feb 13, 2018 at 13:53
  • My final dataframe I want should be having all the cells with its values.There should be no zero elements in it Commented Feb 13, 2018 at 13:55

1 Answer 1

1

You can only export to strings without indices by to_string:

print (df.apply(lambda x: pd.Series(x[x!='0'].values)).fillna(''))
  Z1 Z2 Z3 Z4
0  C  B  A  A
1  D     C   
2        D   
3        E   

df = df.apply(lambda x: pd.Series(x[x!='0'].values)).fillna('').to_string(index=False)
print (df)
Z1 Z2 Z3 Z4
C  B  A  A
D     C   
      D   
      E
Sign up to request clarification or add additional context in comments.

2 Comments

Will it be good if I took these into new dataframe.All the non zero elements
In each Dataframe has to be index, so use df1 = df.apply(lambda x: pd.Series(x[x!='0'].values)).fillna('')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.