【问题标题】:How to strip symbol from pandas data frame column如何从熊猫数据框列中删除符号
【发布时间】: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

标签: python pandas dataframe


【解决方案1】:

您使用的字符串操作方法似乎走在了正确的轨道上。我自己测试了它,df['Price'].str.rstrip(' -') 具有删除尾随空格和连字符的效果。您所缺少的似乎只是对astype 的调用。

df['Price'] = df['Price'].astype(int)

【讨论】:

  • df['Price'].str.rstrip(' -') 没有占用我输出中的空格和连字符。这很奇怪,因为 df['Price'] = df['Price'].str.lstrip('$') 有效地为 $ 工作。
  • 我无法立即想到原因。您是否认为 DataFrame 中当前存在的连字符实际上被编码为其他字符?或者,您可以使用正则表达式删除所有不是 0 到 9 的字符。
  • 当我尝试你给我的 astype 代码时,我收到错误消息“ValueError: invalid literal for int() with base 10: '500\xa0–'” 所以我认为你是对的它被编码为其他一些字符。现在要弄清楚如何将其他角色带走......
  • 如果你想要的子字符串是一个连续的数字序列(字符 0 到 9),你可以使用pd.Series.str.extract 来获取第一个匹配\d+ 的子字符串。
【解决方案2】:

使用 str.extract 或 regex 捕获组仅保留数字 - 如果有小数,则保留小数(否则您将 45.00 变为 4500)。如果您有小数,请使用 astype(float),或者如果您只有整数,则可以忽略 .并使用 astype(int)。这里有两种清理价格列的方法,您只需要一种:

row1list = ['$500 -', 'www']
row2list = ['$4.00 -', 'xyz']
df = pd.DataFrame([row1list, row2list],
                  columns=['Price', 'abc'])

# option 1:  regex capture groups
df['Price'] = df['Price'].str.replace('([0-9]+)', r'\1', regex=True).astype(float)

# option 2:  extract
df['Price'] = df['Price'].str.extract('([0-9.]+)').astype(float)

# print(df)
#    Price  abc
# 0  500.0  www
# 1    4.0  xyz


【讨论】:

  • 太棒了。选项 # 1 现在应该可以工作了,我最初忘记将 .astype(float) 放在最后,所以它仍然是一个字符串。
猜你喜欢
  • 2016-11-03
  • 1970-01-01
  • 2017-07-27
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
相关资源
最近更新 更多