簡體   English   中英

Python pandas 數據框檢查一列的值是否在另一個列表中

[英]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.isinpandas.Series.isin但我pandas.Series.isin正確的語法。 你能幫忙嗎?

您可以組合str.splitstr.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.

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