![](/img/trans.png)
[英]Boolean values to column names in one list, dataframe pandas python
[英]Python pandas dataframe check if values of one column is in another list
我有一個熊貓數據框:
id attr
1 val1
2 val1||val2
3 val1||val3
4 val3
和一個列表special_val = ['val1', 'val2', 'val4']
我想過濾第一個數據框以保留所有attr
值都在列表中的行。 所以我需要結果是這樣的:
id attr
1 val1 #val1 is in special_val
2 val1||val2 #both val1 and val2 are in special_val
我正在考慮使用pandas.DataFrame.isin
或pandas.Series.isin
但我pandas.Series.isin
正確的語法。 你能幫忙嗎?
您可以組合str.split
、 str.split
isin()
和groupby()
:
s = df['attr'].str.split('\|+', expand=True).stack().isin(special_val).groupby(level=0).all()
df[s]
輸出:
id attr
0 1 val1
1 2 val1||val2
您可以嘗試以下操作。
df['match'] = df['attr'].apply(lambda x: True if set(x.split('||')).intersection(set(special_val)) else False)
df[df['match'] == True]
輸出
id attr
0 1 val1
1 2 val1||val2
你可以做:
import numpy as np
special_val = set(['val1', 'val2', 'val4'])
df["attr2"]=df["attr"].str.split("\|\|").map(set)
df=df.loc[df["attr2"].eq(np.bitwise_and(df["attr2"], special_val))].drop(columns="attr2")
輸出:
id attr
0 1 val1
1 2 val1||val2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.