Boomshakalaka
Boomshakalaka

Reputation: 521

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

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.

Upvotes: 2

Views: 100

Answers (2)

fsl
fsl

Reputation: 3280

Here is one slightly faster alternative:

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

Upvotes: 2

Derek O
Derek O

Reputation: 19600

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

Upvotes: 1

Related Questions