Search code examples
pythonpandasconcatenation

Concat values from same column name in "one" dataframe


I want to concat the values if they have same columns.

enter image description here I've found some solutions that are from different dataframe, but not from one dataframe. Also, I tried to separate columns to single dataframe then concat, but it seems not working because the columns' name are shown differently. (For example, it shows "apple", "banana", "pizza", "apple.1", "banana.1"...)

Is there any solution to show like this? Thanks! enter image description here


Solution

  • You can use melt to flatten your dataframe then pivot to reshape it as its original shape:

    df.columns = df.columns.str.rsplit('.').str[0]
    
    out = df.melt().assign(index=lambda x: x.groupby('variable').cumcount()) \
            .pivot_table('value', 'index', 'variable', fill_value=0) \
            .rename_axis(index=None, columns=None)[df.columns.unique()]
    
    print(out)
    
    # Output
       apple  banana  pizza
    0      1       4      4
    1      2       3      7
    2      3       2      3
    3      5       0      1
    4      8       0      5
    5      9       0     34