Python - How to combine the rows into a single row in Pandas? (not group by)

Viewed 52

I am working with a weird dataframe using Pandas:

print(df)

Active        Dead       Hold
Product1      n/a        n/a
n/a           Product2   n/a
n/a           n/a        Product3

I want to combine the three rows into 1 row and the expected output is:

Active        Dead       Hold
Product1      Product2   Product3

I really don't know how to do this and appreciate your help! Thank you.

2 Answers

Here is one slightly faster alternative:

new = df.apply(lambda x: x.dropna().values)

Assuming that dropping NaN from each column of the df yields the same number of rows for each column, you can loop through each column of the df, drop NaN, and place them in a new DataFrame.

df_collapsed = pd.DataFrame()
for col in df.columns:
    df_collapsed[col] = df[col].dropna().values

Output:

df_collapsed

     Active      Dead      Hold
0  Product1  Product2  Product3
Related