How to collapse Pandas Dataframe columns and concatenate rows

I have a Data Frame df0 with n columns. Only one of the columns contains a row, all other columns are empty or contain the string "".

Is it possible to collapse a data frame into a data frame with one column, where for each row I get a non-empty element?

df0:

    A    B     C
1  Car
2  Car 
3       Bike
4  Car
5            Train
6            Train

should give:

    1    
1  Car
2  Car 
3  Bike
4  Car
5  Train
6  Train
+4
source share
3 answers

May be:

>>> df.max(axis=1)
1      Car
2      Car
3     Bike
4      Car
5    Train
6    Train
dtype: object

which is Series, not a DataFrame, but you can do it using df.max(axis=1).to_frame(1)or something else.

+6
source

If these are empty lines, not NaN, you can use .sum:

In [11]: df.fillna('').sum(1)
Out[11]: 
1      Car
2      Car
3     Bike
4      Car
5    Train
6    Train
dtype: object
+4
source

, :

 df.apply(lambda x: [y for y in x.values if y!=''][0],axis=1)
+1

Source: https://habr.com/ru/post/1532377/


All Articles