【问题标题】:Filtering with conditions pandas df containing a list过滤条件 pandas df 包含一个列表
【发布时间】:2021-10-26 17:52:35
【问题描述】:

我有一个 df,它的单元格中有列表对象:

data['country_code']
0       [IT, IT]
1       [PL, PL]
2       [IT, IT]
3       [IT, IT]
4       [IT, IT]
          ...   
6318    [XX, MT]
6319    [FI, FI]
6320    [XX, XX]
6321    [FI, FI]
6322    [FI, FI]
Name: country_code, Length: 6323, dtype: object

如果data['country_code'] 中的列表将'SK''CZ' 作为第一个或第二个元素,我想过滤数据框data

类似这样的:

data[first element of data['country_code'] == 'SK'or'CZ' or second element of data['country_code'] == 'SK'or'CZ']

在 MongoDB 语法中是:

.find({$or: [{country_code: $elemMatch = 'SK'}, {country_code: $elemMatch = 'CZ'}]})

【问题讨论】:

    标签: python pandas list filter conditional-statements


    【解决方案1】:

    你可以使用:

    print(df[df.country_code.apply(lambda x: "SK" in x or "CZ" in x)])
    

    打印:

      country_code
    3     [IT, CZ]
    4     [SK, IT]
    

    df 已使用:

      country_code
    0     [IT, IT]
    1     [PL, PL]
    2     [IT, IT]
    3     [IT, CZ]
    4     [SK, IT]
    

    【讨论】:

    • 工作,你!将在 5 分钟内接受它。顺便说一句,感觉有点像鸡编码。但是它有效!
    【解决方案2】:

    你也可以使用pd.Series.str访问器:

    l = ['SK', 'CZ']
    
    print (data[data['country_code'].str[0].isin(l)|data["country"].str[1].isin(l)])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2021-09-07
      • 2017-08-15
      • 2022-01-23
      • 2019-07-26
      • 2014-02-19
      • 1970-01-01
      相关资源
      最近更新 更多