【发布时间】:2021-09-10 08:45:12
【问题描述】:
我正在尝试将一列文本数字转换为数值,但值的末尾有一个讨厌的“-”,我似乎无法摆脱。
这是我的代码
from bs4 import BeautifulSoup
import pandas as pd
soup = BeautifulSoup(driver.page_source)
items = soup.find("div", {"class": "items-grid-view"})
rows_processed=[]
for item in items.findAll("div", {"class": "item-cell"}):
itemTitle = item.find("a", {"class": "item-title"})
itemPromo = item.find("p", {"class": "item-promo"})
itemPrice = item.find("li", {"class": "price-current"})
row = []
row.append(itemTitle.text)
row.append(itemPromo.text)
offer_tag = itemPrice.find("a")
if offer_tag:
offer_tag.extract()
row.append(itemPrice.text)
rows_processed.append(row)
df = pd.DataFrame.from_records(rows_processed, columns=["Item Title ", "Status", "Price"])
df['Price'] = df['Price'].str.lstrip('$')
df['Price'] = df['Price'].str.rstrip(' -')
df = df.replace(',','', regex=True)
df.replace(to_replace ="-",
value ="")
isAvailable = "Available" in df["Status"].values
print(isAvailable)
display(df)
通过我使用的命令,我已经能够从价格值中去除“C”“$”“”和“(2 Offers)”。但是每个数字之后仍然有一个“-”,即
500 -
450 -
600 -
1200 -
etc
如何去除数据框列中每个值的空格和破折号?
【问题讨论】:
-
在第一个循环中去掉所有这些,然后再将其转换为 DataFrame。然后熊猫就能认出它们是数字。
-
在将其转换为 DataFrame 之前,我应该使用什么函数来剥离它?我正在尝试使用 (itemPrice.replace(" -", "")) 但它返回错误 NoneType object is not callable