如何基于Pandas DataFrame的两列分类数据生成'Mydisciplines'列
生成Pandas DataFrame的'Mydisciplines'列解决方案
嘿,我来帮你搞定这个需求!要生成Mydisciplines列,核心是根据每行的Primary area和Discipline的值来定制内容。我给你两种最常用的实现方式,你可以根据实际需求调整:
方式1:直接拼接两列内容
如果只是想把两个列的内容用分隔符组合起来,直接用字符串拼接就行,代码非常简洁:
import pandas as pd d = { 'Primary area': [ 'Biological Sciences A', 'Cultures and Cultural Production', 'Mathematics' ], 'Discipline': [ 'Biochemistry and Molecular Biology', 'Philosophy', 'Pure Mathematics' ] } df = pd.DataFrame(data=d) # 拼接两列,用" - "作为分隔符 df['Mydisciplines'] = df['Primary area'] + ' - ' + df['Discipline'] # 查看结果 print(df)
运行后得到的DataFrame内容:
Discipline Primary area Mydisciplines 0 Biochemistry and Molecular Biology Biological Sciences A Biological Sciences A - Biochemistry and Molecular Biology 1 Philosophy Cultures and Cultural Production Cultures and Cultural Production - Philosophy 2 Pure Mathematics Mathematics Mathematics - Pure Mathematics
方式2:根据自定义规则生成内容
如果需要针对不同的Primary area设置专属的格式或描述,可以用apply函数自定义逻辑:
import pandas as pd d = { 'Primary area': [ 'Biological Sciences A', 'Cultures and Cultural Production', 'Mathematics' ], 'Discipline': [ 'Biochemistry and Molecular Biology', 'Philosophy', 'Pure Mathematics' ] } df = pd.DataFrame(data=d) # 定义生成Mydisciplines的规则函数 def build_discipline_label(row): # 根据Primary area分类添加前缀 if row['Primary area'] == 'Biological Sciences A': return f"生命科学领域: {row['Discipline']}" elif row['Primary area'] == 'Cultures and Cultural Production': return f"人文社科领域: {row['Discipline']}" elif row['Primary area'] == 'Mathematics': return f"数学领域: {row['Discipline']}" # 处理未匹配到的情况 else: return row['Discipline'] # 应用函数生成新列 df['Mydisciplines'] = df.apply(build_discipline_label, axis=1) # 查看结果 print(df)
运行后得到的DataFrame内容:
Discipline Primary area Mydisciplines 0 Biochemistry and Molecular Biology Biological Sciences A 生命科学领域: Biochemistry and Molecular Biology 1 Philosophy Cultures and Cultural Production 人文社科领域: Philosophy 2 Pure Mathematics Mathematics 数学领域: Pure Mathematics
如果你的规则和上面的示例不一样,只需要修改build_discipline_label函数里的判断逻辑就行——比如提取部分关键词、添加额外标记等,都可以灵活调整。
内容的提问来源于stack exchange,提问作者nahusznaj
相关产品推荐
相关产品推荐

