干猕猴桃
干猕猴桃

Reputation: 305

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.

Upvotes: 2

Views: 364

Answers (1)

anky
anky

Reputation: 75150

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

Upvotes: 3

Related Questions