首页 > 解决方案 > 通过比较列中的字典值来收集 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 收集行。但是如何为字典分配条件我不知道。请帮忙!

标签: pythonpandasdictionary

解决方案


你可以这样做:

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*_中剩余的( )。


推荐阅读