简体   繁体   中英

How to add row name to cell in pandas dataframe?

How do I take data frame, like the following:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df

      col1    col2
row0   1   3
row1   2   4

And produce a dataframe where the row name is added to the cell in the frame, like the following:

        col1     col2
row0   1,row0   3,row0
row1   2,row1   4,row1

Any help is appreciated.

You can convert the dtype to string and add the index to the dataframe:

print(df,'\n')
print(df.astype(str).add(","+df.index,axis=0))

      col1  col2
row0     1     3
row1     2     4 

        col1    col2
row0  1,row0  3,row0
row1  2,row1  4,row1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM