熊猫-根据价值过滤列

时间:2018-11-13 07:03:53

标签: pandas filter

我有一个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”之类的属性的行

谁能帮忙,谢谢

1 个答案:

答案 0 :(得分:2)

如果列表中没有布尔值掩码的行中的键get,并且使用boolean indexing进行过滤,则也可以使用带有Name的列表理解来处理行,

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']]]
相关问题