如何在python中的单元格值旁边添加标题名称 [英] How to add a header name next to its cell value in python

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

问题描述

我将此表作为输入,我想在将标题转换为数据框之前将其名称添加到其对应的单元格中





我想要的表的第一列的示例:

 年龄
年龄= 45
年龄= 30
年龄= 45
年龄= 80



,以此类推。访问各列并重写它们的最佳方法是什么?除了在每个单元格中添加标头名称以外,还有更好的解决方案在生成关联规则之后引用我的值吗?

这是将列名称添加到所有单元格的一种方法:

  df = pd.DataFrame({'age':[ 1,2],'sex':['M','F']})
df = df.applymap(str)

for df.c中的列:
df [c] = df [c] .apply(lambda s: {} = {}。format(c,s))

这将产生:

 年龄性别
0年龄= 1性别= M
1岁= 2性别= F


I have this table as an input and I would like to add the name of the header to its corresponding cells before converting it to a dataframe

I am generating association rules after converting the table to a dataframe and each rule is not clear if it belongs to which antecedent/consequent.

Example for the first column of my desired table:

Age
Age = 45
Age = 30 
Age = 45
Age = 80 

. . and so on for the rest of the columns. What is the best way to access each column and rewrite them? And is there a better solution to reference my values after generating association rules other than adding the name of the header to each cell?

解决方案

Here is one way to add the column names to all cells:

df = pd.DataFrame({'age':[1,2],'sex':['M','F']})
df = df.applymap(str)

for c in df.columns:
    df[c] = df[c].apply(lambda s: "{} = {}".format(c,s))

This yields:

    age     sex
0   age = 1 sex = M
1   age = 2 sex = F

这篇关于如何在python中的单元格值旁边添加标题名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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