簡體   English   中英

如何將 pandas.series.str.contains 方法的結果分配給新列

[英]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列中包含RedNoir ,則將其分配給一個名為Red的新值,並將Red附加到Type列中的該索引。

我使用了熊貓字符串包含方法,但它只返回布爾值,當我嘗試遍歷它時說我不能(當然因為它們是布爾值)。 有誰知道如何解決這個問題??

str.contains應該返回一個布爾數組。 這是因為字符串要么包含您的子字符串,要么不包含。 如果你想覆蓋所有輸出布爾數組為TrueFalse實例,你需要將str.containsnumpy.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接受一個布爾數組,並將值分配給它是TrueFalse任何地方。 在這種情況下,我將"Red"分配給我們的布爾數組為True任何地方,並將"NOT RED"分配給數組為False任何地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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