python - 如何向数据框中的每一列输入一些值

标签 python pandas

如何使用 pandas 在每列的每个值之前添加列名称?

初始数据框:

name Math Physics 

Jack 90    100

Tom  70     95

在每列中添加列名称:

name        Math       Physics 

name:Jack   Math:90    Physics:100

name:Tom    Math:70    Physics:95

最佳答案

添加由 DataFrame.astype 转换为字符串的 DataFrame到列名称:

df = df.columns + ':' + df.astype(str)
print (df)
        name     Math      Physics
0  name:Jack  Math:90  Physics:100
1   name:Tom  Math:70   Physics:95

另一个想法是使用 DataFrame.radd从右侧添加值:

df = df.astype(str).radd(':').radd(df.columns)
print (df)
        name     Math      Physics
0  name:Jack  Math:90  Physics:100
1   name:Tom  Math:70   Physics:95

关于python - 如何向数据框中的每一列输入一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560891/

相关文章:

python - 在 Z3Py 中编码可接受的集合

Python:如何使用 BeautifulSoup 查找第一个 anchor 标记的文本

python - 考虑重叠情况下确定总时间的有效方法

python - 通过检查多列上的条件来创建新变量

python - 从 Google DataStore 打印多个二进制数据字段?

Python3 - 将非 ascii 字符替换为其 unicode 代表值?

python - QDialog - 防止在 Python 和 PyQt 中关闭

python - Pandas 将列转换为总数的百分比

pandas - 值错误: object of too small depth for desired array,

python - 使用 Pandas 替换不同列的元素