pandas - 如果 dtype 列表(对象)列中的值具有特定值,则查找行

给定如下数据框


   A  B  C-1  D  BTP           Type C1           Type C2

0  0  1    0  0    0               NaN          [Type B]

1  0  2    1  1   14          [Type B]          [Type B]

2  0  3    2  2   28          [Type A]          [Type B]

3  0  4    3  3   42  [Type A, Type B]  [Type A, Type B]

4  0  5    4  4   56          [Type A]  [Type A, Type B]

想要获取具有Type A列值的行Type C1和应返回行索引 342的列。BTP


尝试了以下,但给出了错误KeyError: False


df.loc[(df['BTP'] == 42) & ('Type A' in df['Type C1'])]

我最终想要做的是获取符合上述条件的行(这将是单行)并提取列的值B并C-1作为字典{'B_val': 4, 'C_val': 3}


白衣非少年
浏览 160回答 3
3回答

冉冉说

您可以使用>>> type_a = df['Type C1'].apply(pd.Series).eq('Type A').any(1)>>> df[df['BTP'].eq(42) & type_a]   A  B  C-1  D  BTP           Type C1           Type C23  0  4    3  3   42  [Type A, Type B]  [Type A, Type B]

qq_遁去的一_1

使用,Series.str.join连接列中的列表Type C1,然后我们可以Series.str.contains在此列上使用来检查给定的字符串 ieType A是否存在于系列中,最后我们可以使用布尔值过滤数据帧的行mask:mask = df['BTP'].eq(42) & df['Type C1'].str.join('-').str.contains(r'\bType A\b')df = df[mask]结果:# print(df)   A  B  C-1  D  BTP           Type C1           Type C23  0  4    3  3   42  [Type A, Type B]  [Type A, Type B]

BIG阳

我使用自定义函数解决了这个问题,根据所考虑的列表是否包含“类型 A”,为每一行返回真/假值列表。# Check if elem is present in column 'col'def has_elem(col, elem):    result = []    for c in col:        if elem in c:            result.append(True)        else:            result.append(False)    return result# Filterdf.loc[(df['BTP'] == 42) & has_elem(df['Type_C1'], 'Type A'), :]您的代码不起作用的原因是因为第二个过滤器子句在 Series 对象中'Type A' in df['Type_C1']查找字符串的成员资格,并因此返回。相反,您需要返回一系列 True/False 值,数据框中的每一行 1。'Type A'df['Type_C1']False
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python