簡體   English   中英

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

[英]pandas - find rows if values in column of dtype list (object) has specific value

給定如下數據框

   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 C1列獲取值為Type A的行,為BTP列獲取值為42的行,這應該返回行索引 3。

嘗試了以下,但給出了錯誤KeyError: False

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

我最終要做的是獲取與上述條件匹配的行(這將是單行)並將列BC-1的值提取為像{'B_val': 4, 'C_val': 3}

使用Series.str.join加入Type C1列中的列表,然后我們可以在該列上使用Series.str.contains來檢查給定的字符串,即Type A是否存在於系列中,最后我們可以使用 boolean mask過濾 dataframe 的行:

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 C2
3  0  4    3  3   42  [Type A, Type B]  [Type A, Type B]

您可以使用

>>> 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 C2
3  0  4    3  3   42  [Type A, Type B]  [Type A, Type B]

我使用自定義 function 解決了這個問題,根據考慮的列表是否包含“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

# Filter
df.loc[(df['BTP'] == 42) & has_elem(df['Type_C1'], 'Type A'), :]

您的代碼不起作用的原因是因為 df['Type_C1'] 中的第二個過濾器子句'Type A' in df['Type_C1']查找 object df['Type_C1']系列中字符串'Type A'的成員資格,因此返回False . 相反,您需要為 dataframe 中的每一行返回一個真/假值序列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM