關于如何查看某個單詞是否在pandas列內的提示?
# initialise data of lists.
data = {'Colour': ['Blue andtext', 'Greys', 'potato', 'Yellow','Tree'] 。
'Values':[20, 21, 19, 18,44]} 。
df2 = pd.DataFrame(data)
我們說:
colours = ['Blue','Grey','Yellow']
我如何檢查df2['Colour']是否真的是一種顏色,并在一個新的列中表示它?
輸出應該是
Colour Value Actualcolour
藍色和文本 20 藍色
灰色 21 灰色
馬鈴薯 19 NaN
黃色 18 黃色
樹木 44 Nan
uj5u.com熱心網友回復:
這樣如何?
df2['ActualColour'] = [x ifx in colorselse np. NaN for x in df2.Colour] 。
你也可以把colours轉換成df,然后左鍵連接它們
uj5u.com熱心網友回復:
使用pd.Series.where和isin:
df2["Actualcolour"] = df2["Colour"].where(df2["Colour").isin( colours)
print (df2)
顏色值 實際顏色
0 藍色 20 藍色
1 灰色 21 灰色
2 土豆 19 NaN
3 黃色 18 黃色
4 Tree 44 NaN
或者使用pd.Series.extract,如果需要的話,添加單詞邊界或忽略大小寫:
df2["ActualColor"] = df2["Color"]。 str.extract(f"({'|'.join(color)})")
print (df2)
顏色值 實際顏色
0 Blue andtext 20 Blue
1灰色 21灰色
2 馬鈴薯 19 NaN
3 黃色 18 黃色
4 Tree 44 NaN
uj5u.com熱心網友回復:
另一個可能的答案是使用.apply將一個函式應用于有關的列:
df2["ActualColour"] = df2["Color"] 。 apply(lambda x: x if x in colors else np.nan)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/327330.html
標籤:
