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.

3 answers

  • answered 2018-02-13 01:27 unutbu

    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
    

  • answered 2018-02-13 01:27 Allen

    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
    

  • answered 2018-02-13 01:27 Wen

    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