pandas - 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”之类的属性的行
谁能帮忙,谢谢
解决方案
如果某些行中不存在布尔掩码的键并按以下方式过滤,则使用列表推导get
来处理行:Name
boolean 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']]]
推荐阅读
- python - 当请求输入是元素列表时,蝗虫发布请求错误
- javascript - 在单行中对齐两个表
- javascript - 使用 Firebase 登录 Microsoft Teams 自定义选项卡
- r - R for lm 中的 autoplot():为什么我得到“恒定杠杆:残差与因子水平”而不是“残差与杠杆”图?
- c# - CollectionViewController 使用 c# 显示黑色背景,没有图像
- sql - ALL_TABLES、count(*) 和 count(PRIMARY_KEY) 有什么区别?
- sql - 如何获取与组中最新日期对应的值以填充 Oracle SQL 中的空值?
- flutter - Flutter localstorage.getItem() 返回 null
- python - “for”循环不继续(python)
- python - 如何取消选择在 kivy filechooser 列表视图中选择的多个文件