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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With