【问题标题】:How to create a column in a dataframe using filtering for string values from a list?如何使用过滤列表中的字符串值在数据框中创建列?
【发布时间】:2023-01-31 14:31:37
【问题描述】:

我有以下格式的数据框(实际数据框包含超过 10000 行)

Occupation                  Education
Engineer                    High School    
Neurosurgeon                Masters
Electrical Engineer         Masters
Mechanical Engineer         Masters
Software Engineer           Masters
Engineer                    Masters
Business Executive          Masters
Sales Executive             Bachelors
Neurosurgeon                Masters
Electrical Engineer
Accountant                  Bachelors
Sales Executive             Masters

我想添加一个基于选择性过滤的列

我需要我的结果是这样的

Occupation                  Education               Welfare_Cost
Engineer                    High School             50 
Neurosurgeon                Masters                 50
Electrical Engineer         Masters                 100
Mechanical Engineer         Masters                 100
Software Engineer           Masters                 100
Engineer                    Masters                 100
Business Executive          Masters                 100
Sales Executive             Bachelors               50
Neurosurgeon                Masters                 50
Electrical Engineer                                 50
Accountant                  Bachelors               50 
Sales Executive             Masters                 100

我只想处理职业包含列表中的字符串并且教育是大师的行我尝试使用以下代码来实现这一点,但不断出现错误。


lis=['Engineer','Executive','Teacher']

df['Welfare_Cost']=np.where(((df['Education']=='Masters')&
                        (df['Occupation'].str.contains(i for i in lis))),        
                      100,50)

我知道我也可以通过运行迭代循环来为每一行创建一个列表并将该列表添加为一列来做到这一点,但是我有很多列表组合,所以我正在寻找一种无需使用交互式就可以做到这一点的方法环形。

【问题讨论】:

    标签: python pandas dataframe numpy filter


    【解决方案1】:

    利用:

    df['Welfare_Cost']=np.where(((df['Education']=='Masters')& (df['Occupation'].str.contains('|'.join(lis)))),
    

    100,50)

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2021-01-30
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2019-03-04
      • 2016-03-21
      相关资源
      最近更新 更多