You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame嵌套列匹配:如何获取完整匹配行数据

解决方案

方法一:用Pandas布尔索引(推荐,更高效)

不用手动遍历,直接借助Pandas的apply生成匹配条件的布尔掩码,就能直接筛选出完整的DataFrame行:

匹配Row对象的a字段

以匹配a='abc'为例:

# 生成布尔掩码:检查每一行的nested_col列中,是否存在Row的a字段等于目标值
mask_a = df['nested_col'].apply(lambda rows: any(row.a == 'abc' for row in rows))
# 筛选出符合条件的完整行
result_a = df[mask_a]
print(result_a)

匹配Row对象中c列表的元素

以匹配c列表包含'089'为例:

# 生成布尔掩码:检查每一行的nested_col列中,是否存在Row的c列表包含目标元素
mask_c = df['nested_col'].apply(lambda rows: any('089' in row.c for row in rows))
# 筛选出符合条件的完整行
result_c = df[mask_c]
print(result_c)

方法二:修改自定义函数关联原DataFrame

你之前的函数只遍历了nested_col列的内容,没有关联原DataFrame的行数据。可以改为遍历整个DataFrame的行,同时记录索引,找到匹配项时直接取出整行:

def find_a(df, a_value):
    # 遍历DataFrame的每一行,同时获取索引和行数据
    for idx, df_row in df.iterrows():
        # 遍历当前行中的Row对象列表
        for nested_row in df_row["nested_col"]:
            if nested_row.a == a_value:
                # 返回完整的DataFrame行
                return df.loc[idx]
                # 如果要输出所有匹配行,替换return为print(df.loc[idx])即可

# 调用函数,传入整个DataFrame和目标值
matched_row = find_a(df, "abc")
print(matched_row)

同理,匹配c列表元素的函数可以这样写:

def find_c(df, c_value):
    for idx, df_row in df.iterrows():
        for nested_row in df_row["nested_col"]:
            if c_value in nested_row.c:
                return df.loc[idx]

matched_row = find_c(df, "089")
print(matched_row)

内容的提问来源于stack exchange,提问作者Rayne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 19:12:33