Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy the column headers of a data frame to each row value?

I'm trying to transform a pandas data frame, applying a function to all values, to concatenate the column header and the actual value.

My original dataframe is something like this:

|---------------------|------------------|
|         Col1        |        Col2      |
|---------------------|------------------|
|          12         |         34       |
|---------------------|------------------|
|          12         |         34       |

The output should be:

|---------------------|------------------|
|       Col1          |      Col2        |
|---------------------|------------------|
|       Col1_12       |      Col2_34     |
|---------------------|------------------|
|       Col1_12       |      Col2_34     |

What I tried is this:

mypandasdf.applymap(lambda x: 'columnname'+'_'+str(x))

But I'm struggling with the column name value. How can I put the real column name instead of a string? Or is there any other/better way to do it?

like image 797
César Requena Avatar asked Oct 30 '25 12:10

César Requena


1 Answers

df = pd.DataFrame({'colA': [12,34], 'colB': [56,78]})

df = df.columns.values + '_' + df.astype(str)

print(df)

Output:

      colA     colB
0  colA_12  colB_56
1  colA_34  colB_78
like image 56
perl Avatar answered Nov 02 '25 02:11

perl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!