Home > OS >  Concat values from same column name in "one" dataframe
Concat values from same column name in "one" dataframe

Time:03-27

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

CodePudding user response:

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

out = df.rename(columns=lambda x: x.rsplit('.')[0]) \
        .melt().assign(index=lambda x: x.groupby('variable').cumcount()) \
        .pivot_table('value', 'index', 'variable', fill_value=0) \
        .rename_axis(index=None, columns=None)
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
  • Related