3 回答

TA貢獻1877條經驗 獲得超1個贊
您可以使用
>>> 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]

TA貢獻1725條經驗 獲得超8個贊
使用,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 C2
3 0 4 3 3 42 [Type A, Type B] [Type A, Type B]

TA貢獻1859條經驗 獲得超6個贊
我使用自定義函數解決了這個問題,根據所考慮的列表是否包含“類型 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'), :]
您的代碼不起作用的原因是因為第二個過濾器子句在 Series 對象中'Type A' in df['Type_C1']查找字符串的成員資格,并因此返回。相反,您需要返回一系列 True/False 值,數據框中的每一行 1。'Type A'df['Type_C1']False
添加回答
舉報