[英]Drop row in pandas if it contains condition
我正在嘗試根據“價格”列中的單元格中是否包含“/”來刪除 pandas 中的行。 我提到了這個問題: 如果 pandas 中包含“???”,則刪除行 .
因此,我嘗試了兩種代碼:
df = df[~df["Price"].str.contains('/')]
和
df = df[~df["Price"].str.contains('/',regex=False)]
但是,兩個代碼都給出了錯誤: AttributeError: Can only use.str accessor with string values!
作為參考,我的dataframe的前幾行如下:
Fruit Price
0 Apple 3
1 Apple 2/3
2 Banana 2
3 Orange 6/7
我可以知道出了什么問題,我該如何解決這個問題? 非常感謝!
嘗試這個:
df = df[~df['Price'].astype(str).str.contains('/')]
print(df)
Fruit Price
0 Apple 3
2 Banana 2
您需要先將價格列轉換為字符串,然后再應用此操作。 我相信價格列沒有數據類型字符串
df['Price'] = df['Price'].astype(str)
然后嘗試
df = df[~df["Price"].str.contains('/',regex=False)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.