[英]Filter Pandas by a Column with List Values
給定一個包含帶有列表值的列的DataFrame
> pd.DataFrame.from_dict(
{'name' : {0 : 'foo', 1: 'bar', 2: 'baz', 3: 'foz'},
'Attributes': {0: ['x', 'y'], 1: ['y', 'z'], 2: ['x', 'z'], 3: []}
})
name Attributes
0 foo ['x', 'y']
1 bar ['y', 'z']
2 baz ['x', 'z']
3 foz []
如何僅針對列表中不包含特定值(例如'y'
那些行過濾 DataFrame:
2 baz ['x', 'z']
3 foz []
預先感謝您的考慮和回應。
您可以將列表系列轉換為數據框並比較所有列是否不等於y
:
# is they aren't actual list : df['Attributes'] = df['Attributes'].apply(ast.literal_eval)
df[pd.DataFrame(df['Attributes'].tolist()).ne('y').all(1)]
Name Attributes
2 baz [x, z]
如果它們不是實際列表:
df[df['Attributes'].str.count('y').eq(0)]
這應該有效(雖然它不是很優雅)
def filter_data_frame(df):
good_index = []
for i in range(len(df)):
if "y" not in df.iloc[i,1]:
good_index.append(i)
return df.iloc[good_index, :]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.