[英]Remove pandas dataframe row if one column's element is non-numeric
我一直在為這個簡單的事情尋找答案一個小時。 我有一個 pandas dataframe 看起來像這樣:
title | price
"some text 1" 124.5
"some text 2" 543.2
"some text 3" 156.2
"some text 4" "Price N/A"
"some text 5" 216.7
我想刪除不包含實際浮動價格的行。 我嘗試了這個答案的建議:
raw_data[raw_data.price.apply(lambda x: x.isnumeric())]
我得到:
AttributeError: 'float' object has no attribute 'isnumeric'
如此簡單的操作似乎沒有任何效果。 我嘗試了幾乎所有在堆棧和其他地方找到的答案。
您可以使用 pandas 的“to_numeric”操作,當滿足字符串值時會拋出錯誤。 此錯誤將由“強制”處理,強制內容為 null。 然后我們使用“notnull”操作來過濾這個特定的行。
df[pd.to_numeric(df['price'], errors='coerce').notnull()]
您會收到一個錯誤,因為您在float
上應用(lambda x: x.isnumeric())
。
float.isnumeric()
不存在,但您可以使用isinstance(x, t)
,如果 x 屬於 t 類型,則返回True
。
raw_data[raw_data['price'].apply(lambda x : isinstance(x, float))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.