Home > other >  Combine first pandas but keeping columns name in new column
Combine first pandas but keeping columns name in new column

Time:08-25

I have a pandas dataframe with the following form:

  V1    V2
0 10.0  NaN
1 NaN   15.0
2 5.0   NaN
3 NaN   10.0

and I want to combine columns V1 and V2 and have the result be

  V    column_name
0 10.0 V1  
1 15.0 V2   
2 5.0  V1   
3 10.0 V2   

I have tried pandas.combine_first but I can't reach an optimal solution.

CodePudding user response:

res = (df
       .stack()
       .reset_index(level=1)
       .set_axis(["column_name", "V"], axis=1)
       )

This should output :

  column_name     V
0          V1  10.0
1          V2  15.0
2          V1   5.0
3          V2  10.0

CodePudding user response:

I think you need to do a df.stack(). This is my example:

import pandas as pd
import numpy as np

df = pd.DataFrame({"V1":[10, np.nan, 5, np.nan], "V2":[np.nan, 15, np.nan, 10]})
df = df.stack()

Output:

0  V1    10.0
1  V2    15.0
2  V1     5.0
3  V2    10.0
dtype: float64

Be careful, the output is a Series object, so you should cast it to assign column names.

  • Related