Skip to main content
 首页 » 编程设计

python之从两个类别列 pandas 创建一个类别列

2024年09月07日8xing901022

我有这个数据框

d = { 
    'Primary area': [ 
        'Biological Sciences A', 
        'Cultures and Cultural Production', 
        'Mathematics' 
    ], 
    'Discipline': [ 
        'Biochemistry and Molecular Biology', 
        'Philosophy', 
        'Pure Mathematics' 
    ] 
} 
 
import pandas as pd 
 
df = pd.DataFrame(data=d) 
 
    Discipline                              Primary area 
0   Biochemistry and Molecular Biology      Biological Sciences A 
1   Philosophy                              Cultures and Cultural Production 
2   Pure Mathematics                        Mathematics 

我想获得一个新列“Mydisciplines”列,根据行从“Discipline”或“Primary area”中获取项目。我有一个单词列表

Mydisciplines = ['Biological Sciences A', 'Mathematics', 'Philosophy'] 

我想使用这个新列表来过滤两列,然后合并剩下的内容。比如

    Discipline                           Mydisciplines          Primary area 
0   Biochemistry and Molecular Biology   Biological Sciences A  Biological Sciences A 
1   Philosophy                           Philosophy             Cultures and Cultural Production 
2   Pure Mathematics                     Mathematics            Mathematics 

我尝试了一些方法,但无法在一段代码中综合我想要的内容。 我完全不知道如何解决这个问题。

请您参考如下方法:

我相信需要extract通过 | 加入 Mydisciplines 的所有值,用于正则表达式 OR 和 \b 用于单词边界:

Mydisciplines = ['Biological Sciences A', 'Mathematics', 'Philosophy'] 
 
pat = r'(\b{}\b)'.format('|'.join(Mydisciplines)) 
 
#join columns together 
s = df['Discipline'] + ' ' + df['Primary area'] 
 
df['Mydisciplines'] = s.str.extract(pat, expand=False) 
print (df) 
                           Discipline                      Primary area  \ 
0  Biochemistry and Molecular Biology             Biological Sciences A    
1                          Philosophy  Cultures and Cultural Production    
2                    Pure Mathematics                       Mathematics    
 
           Mydisciplines   
0  Biological Sciences A   
1             Philosophy   
2            Mathematics