如何将列名称添加到pandas数据框中的单元格?

Stu*_*ent 5 python-3.x pandas

如何获取正常的数据框,如下所示:

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

    col1    col2
0   1   3
1   2   4
Run Code Online (Sandbox Code Playgroud)

并生成一个数据框,其中列名称添加到框架中的单元格中,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

unu*_*tbu 5

创建一个包含字符串的新 DataFrame col*=,然后将其添加到原始 DataFrame df,并将其值转换为字符串。您会得到所需的结果,因为加法连接字符串:

>>> 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
Run Code Online (Sandbox Code Playgroud)