Student
Student

Reputation: 1197

How to add column name to cell in pandas dataframe?

How do I take a normal data frame, like the following:

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

    col1    col2
0   1   3
1   2   4

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

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

    col1    col2
0   col1=1  col2=3
1   col1=2  col2=4

Any help is appreciated.

Upvotes: 5

Views: 4027

Answers (3)

BENY
BENY

Reputation: 323226

You can try this

df.ne(0).mul(df.columns)+'='+df.astype(str)
Out[1118]: 
     col1    col2
0  col1=1  col2=3
1  col1=2  col2=4

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19947

You can use apply to set column name in cells and then join them with '=' and the values.

df.apply(lambda x: x.index+'=', axis=1)+df.astype(str)
Out[168]: 
     col1    col2
0  col1=1  col2=3
1  col1=2  col2=4

Upvotes: 2

unutbu
unutbu

Reputation: 879133

Make a new DataFrame containing the col*= strings, then add it to the original df with its values converted to strings. You get the desired result because addition concatenates strings:

>>> pd.DataFrame({col:str(col)+'=' for col in df}, index=df.index) + df.astype(str) 
     col1    col2
0  col1=1  col2=3
1  col1=2  col2=4

Upvotes: 5

Related Questions