匹配 pandas 数据框中的嵌套列

问题描述 投票:0回答:1

我有一个包含 5 列的 pandas 数据框,其中一列是列表。如果我只打印列表,我会得到这样的结果:

Row(a='abc',b='def',c=['qwe','rty'])
Row(a='123',b='456',c=['789','089'])
...

我正在努力在球场上匹配

a
,也在名单上
c
(单独)。例如,如果我匹配
a='abc'
,我将获得第一行(包含所有 5 列的整个数据框),如果我匹配
089
中的
c
,我将获得第二行(整个数据框)包含所有 5 列)。

我编写了这个函数来匹配

a
,但结果仅包含
Row
,即没有其他 4 个非嵌套列。我不知道如何从比赛中引用数据框本身。有没有一种方法可以匹配并获取与
a
c
中的元素匹配的数据帧?

def find_a(nested_col_list, a_value):
    for nested_cols in nested_col_list:
        for nested_col in nested_cols:
            if nested_col.a == a_value:
                print(nest_col)

find_a(df["nested_col"], "abc")
python pandas dataframe
1个回答
0
投票

好吧,仔细考虑你所写的内容后,我相信我明白你想要什么。 所以现在你只得到这个嵌套列的行...而你想要的是这个特定嵌套列实例的主数据帧的整行。
因此你有两个选择...要么 enumerate 要么nested_col_list 这样你就有了一个索引并从函数中返回它。下面是函数返回数据帧中发生匹配的索引的示例(例如,这返回匹配的第一行。

def find_a(nested_col_list, a_value):
    for idx,nested_cols in enumerate(nested_col_list):
        for nested_row in nested_cols: #renamed the variable to be more appropriate as to what it is referencing
            if nested_row.a == a_value:
                return idx # This will return the index in the dataframe of the first occurrence where a is found.
            #you can also search c for the value as well.

find_a(df["nested_col"], "abc")

或者,如果您需要从同一个函数访问数据帧(例如使用 print ),那么您将必须将整个数据帧传递给该函数......话虽如此。我将写一个这样做的例子:

ef find_a(df, a_value):
    nested_col_list = df["nested_col"]
    for idx,nested_cols in enumerate(nested_col_list):
        for nested_row in nested_cols: #renamed the variable to be more appropriate as to what it is referencing
            if nested_row.a == a_value:
                print(df[[idx]]) #This will print out the entire row as well as the nested column.
            #you can also search c for the value as well.

find_a(df, "abc")

如果这不是您想要的,请在投票之前澄清您的问题。希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.