![](/img/trans.png)
[英]How to check if string in list of strings is in pandas dataframe column
[英]How do I check dataframe column value in list of strings?
我有一個數據df_b
df
並希望從中創建一個新的數據df_b
,但只使用行數組df['id']
值在我的列表數組list_of_ids
。
df['id']
和list_of_ids
都包含字符串值。
我考慮過使用正則表達式,但是由於list_of_ids
的長度> 20個元素,因此正則表達式將非常龐大,因此需要在list_of_ids
一個生成器,但是我不知道如何應用它。
我在想類似的東西:
list_of_ids = ["thing1", "thing2", "thing3" ]
df_b = df[df["id"].apply(lambda x: x in list_of_ids)==True]
或者,我可以使用.str.contains()
方法,但是傳遞一個由list_of_ids
所有元素構建的字符串,這些元素之間用豎線'|'分隔,但這似乎並不“干凈”。
生成樣本DataFrame:
n = 50
df = pd.DataFrame({
'id': list(string.ascii_letters[:n]),
'n': range(n)})
df.head()
Out:
id n
0 a 0
1 b 1
2 c 2
3 d 3
4 e 4
從ids
列表中選擇ID匹配值的值:
ids = ['a', 'd', 'x', 'A']
df[df['id'].isin(ids)]
Out:
id n
0 a 0
3 d 3
23 x 23
26 A 26
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.