python - 通过比较列中的字典值来收集 DataFrame 行
问题描述
我有一个包含字典的列的 DataFrame。我的任务是比较 dict 中的前两个值,如果它们相等,那么我想收集整行。我无法显示我的任何代码,因为我真的不知道如何组织它。但我将创建一个我的 DF 的小例子,以使情况更清楚。
import pandas as pd
test = pd.DataFrame({'one':['hello', 'there', 'every', 'body'],
'two': ['a', 'b', 'c', 'd'],
'dict': [{'composition': 12, 'process': 4, 'pathology': 4},
{'food': 9, 'composition': 9, 'process': 6, 'other_meds': 3},
{'process': 2},
{'composition': 6, 'other_meds': 6, 'pathology': 2, 'process': 1}]})
test
所以数据看起来像这样:
one two dict
0 hello a {'composition': 12, 'process': 4, 'pathology': 4}
1 there b {'food': 9, 'composition': 9, 'process': 6, 'other_meds': 3}
2 every c {'process': 2}
3 body d {'composition': 6, 'other_meds': 6, 'pathology': 2, 'process': 1}
我的目标是收集索引为 1 和 3 的新 DataFrame 行,因为 dict 的两个第一个值是相同的'food': 9, 'composition': 9
并且'composition': 6, 'other_meds': 6
. 索引号为 0 的行具有相同的值,但这并不有趣,因为它们不在第一和第二位置。
我知道我们正在使用 loc
并 iloc
收集行。但是如何为字典分配条件我不知道。请帮忙!
解决方案
你可以这样做:
import pandas as pd
test = pd.DataFrame({'one': ['hello', 'there', 'every', 'body'],
'two': ['a', 'b', 'c', 'd'],
'dict': [{'composition': 12, 'process': 4, 'pathology': 4},
{'food': 9, 'composition': 9, 'process': 6, 'other_meds': 3},
{'process': 2},
{'composition': 6, 'other_meds': 6, 'pathology': 2, 'process': 1}]})
def equal_values(d):
try:
# extract first and second value
first, second, *_ = d.values()
return first == second
except ValueError:
return False # if there are not two values
res = test[test['dict'].apply(equal_values)]
print(res)
输出
one two dict
1 there b {'food': 9, 'composition': 9, 'process': 6, 'o...
3 body d {'composition': 6, 'other_meds': 6, 'pathology...
符号:
first, second, *_ = d.values()
被称为扩展可迭代解包,请参阅此答案以获得广泛的解释,并查看此帖子以获得入门级教程。
它上面的特殊情况意味着取第一个,第二个忽略values*_
中剩余的( )。
推荐阅读
- javascript - 如何从文件中执行 JavaScript
- batch-file - 命令在命令行上运行,但在批处理文件中意外运行
- php - Yii2:如何使用mysql在Find()的orderby()中添加两个字段和NULLS LAST
- eclipse - Xtext DSL 插件只为文件的第一行提供关键字建议
- c# - 使用上下文声明权限值
- jquery - 如何使 peoplepicker 字段在 SP 2016 上只读
- javascript - 循环遍历 2 个数组
- google-cloud-platform - 无法从 GKE 访问具有私有 IP 的 GCP MySQL
- http-live-streaming - 生成 M3U8 HLS 播放列表时,是否应该包含尚不存在的媒体片段?
- javascript - 为什么事件侦听器中的“this”是窗口而不是元素?