![](/img/trans.png)
[英]pandas.Series.str.contains() is not finding a string which exists in the Series
[英]How do I assign the results of a pandas.series.str.contains method in pandas to a new column
我有以下代碼:
import pandas
dict1 = {
"Country" :['USA','France', 'Spain', 'Italy', 'Germany', 'South Africa', 'Portugal', 'Brazil'],
"Variety" : ['Pinot Gris', 'Pinot Blanc', 'White Blend', 'Sauvignon Blanc', 'Frappato', 'Portuguese Red', 'Red Blend', 'Pinot Noir'],
"Grade" : [80, 85, 83, 87, 88, 89, 84, 86],
}
df = pandas.DataFrame(dict1)
df['Type'] = ''
我想要做的是遍歷每一行,如果一個值在Variety
列中包含Red
或Noir
,則將其分配給一個名為Red
的新值,並將Red
附加到Type
列中的該索引。
我使用了熊貓字符串包含方法,但它只返回布爾值,當我嘗試遍歷它時說我不能(當然因為它們是布爾值)。 有誰知道如何解決這個問題??
str.contains
應該返回一個布爾數組。 這是因為字符串要么包含您的子字符串,要么不包含。 如果你想覆蓋所有輸出布爾數組為True
或False
實例,你需要將str.contains
與numpy.where
結合起來:
import numpy as np
df["Type"] = np.where(df["Variety"].str.contains(r"Red|Noir"), "Red", "NOT RED")
print(df)
Country Variety Grade Type
0 USA Pinot Gris 80 NOT RED
1 France Pinot Blanc 85 NOT RED
2 Spain White Blend 83 NOT RED
3 Italy Sauvignon Blanc 87 NOT RED
4 Germany Frappato 88 NOT RED
5 South Africa Portuguese Red 89 Red
6 Portugal Red Blend 84 Red
7 Brazil Pinot Noir 86 Red
np.where
接受一個布爾數組,並將值分配給它是True
或False
任何地方。 在這種情況下,我將"Red"
分配給我們的布爾數組為True
任何地方,並將"NOT RED"
分配給數組為False
任何地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.