Reputation: 4630
How can I add the pandas column's names to each value inside the rows?, for example, lets say I have the following pandas dataframe:
COL1 COL2 COL3 COL4 ... COL_N
True NO 90.9 2 ... 2018-05-17 20:14:00
True NO 89.11 2 ... 2018-05-17 20:15:32
............
True NO 67.89 1 ... 2018-05-17 20:18:45
How can I turn it into:
COL1 COL2 COL3 COL4 ... COL_N
True (COL1) NO (COL2) 90.9 (COL3) 2 (COL4) ... 2018-05-17 20:14:00 (COL_N)
True (COL1) NO (COL2) 89.11 (COL3) 2 (COL4) ... 2018-05-17 20:15:32 (COL_N)
............
True (COL1) NO (COL2) 67.89 (COL3) 1 (COL4) ... 2018-05-17 20:18:45 (COL_N)
I want to do this because im analyzing some patterns inside each rows. One of the issues is that I am dealing with a large pandas dataframe (500x100000) columns. Any idea of how given a pandas data frame attach its column names to each values?
Upvotes: 2
Views: 3724
Reputation: 18906
Another way would be to loop the columns and use loc.
for col in df.columns:
df.loc[:,col] = df[col].astype(str) + ' ({})'.format(col)
Upvotes: 1
Reputation: 323226
Use :
df.astype(str).apply(lambda x : x+' '+x.name)
Out[7]:
COL1 COL2 COL3 COL4
0 True COL1 NO COL2 90.9 COL3 2 COL4
1 True COL1 NO COL2 89.11 COL3 2 COL4
Upvotes: 8