如何在pandas数据框中的单元格中添加列名称? [英] How to add column name to cell in pandas dataframe?

查看:442
本文介绍了如何在pandas数据框中的单元格中添加列名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

感谢您的帮助.

推荐答案

制作一个包含col*=字符串的新DataFrame,然后将其添加到原始df中,并将其值转换为字符串.由于加法将字符串连接在一起,因此您得到了期望的结果:

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

这篇关于如何在pandas数据框中的单元格中添加列名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆