首页 > 解决方案 > Pandas - 根据值过滤掉列

问题描述

我有一个 Pandas 数据框,它有如下两列(带标题查看):

name,attribute
abc,{'attributes': {'type': 'RecordType', 'url': '/services/data/v38.0/sobjects/RecordType/000xyz'}, 'Name': 'Product 1'}
def,{'attributes': {'type': 'RecordType', 'url': '/services/data/v38.0/sobjects/RecordType/000abc'}, 'Name': 'Product 2'}
klm,{'attributes': {'type': 'RecordType', 'url': '/services/data/v38.0/sobjects/RecordType/000abc'}, 'Name': 'Product 2'}

如何过滤掉具有“产品 1”之类的属性的行

谁能帮忙,谢谢

标签: pandasfilter

解决方案


如果某些行中不存在布尔掩码的键并按以下方式过滤,则使用列表推导get来处理行:Nameboolean indexing

df = df[[x.get('Name') == 'Product 1' for x in df['attribute']]]

或者:

df = df[df['attribute'].apply(lambda x: x.get('Name')) == 'Product 1']
#alternative, working if all Name exist in each row
#df = df[df['attribute'].apply(lambda x: x['Name']) == 'Product 1']

print (df)
  name                                          attribute
0  abc  {'attributes': {'type': 'RecordType', 'url': '...

编辑:

如果还想按嵌套字典过滤:

df = df[[x.get('attributes').get('type') == 'RecordType' for x in df['attribute']]]

推荐阅读