【问题标题】:How do I strip the "$" symbol from a string in a pandas series?如何从熊猫系列中的字符串中去除“$”符号?
【发布时间】:2020-07-19 10:28:27
【问题描述】:

急需帮助。我正在尝试有条件地迭代 Google Play 商店 csv 文件的行。由于某种原因,在我的某些循环中,我一直遇到 pandas 无法识别 '>=' 符号的问题。也就是说,使用条件 "if price == "9.00" 可以正常工作,但其他操作(即 '=" 返回错误消息。

此外,我正在尝试计算价格为 9.00 美元或更高的应用数量。我想从价格列中去掉“$”符号,然后继续迭代它。我尝试了 str.lstrip 函数但没有成功。非常感谢任何和所有帮助。


df = pd.read_csv("googleplaystore.csv")

df['Rating'].fillna(value = '0.0', inplace = True)

# Calculating how many apps have a price of $9.00 or greater

apps_morethan9 = 0

for i, row in df.iterrows():
    rating = float(row.Rating)
    price = float(row.Price)
    if price >= 9:
        apps_morethan9 += 1

print(apps_morethan9)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-103-66171ce7efb6> in <module>
      5 for i, row in df.iterrows():
      6     rating = float(row.Rating)
----> 7     price = float(row.Price)
      8     if price >= 9:
      9         apps_morethan9 += 1

ValueError: could not convert string to float: '$4.99'``` 

【问题讨论】:

  • row.Price.str.strip("$")?或str.lstrip("$")

标签: python pandas loops if-statement conditional-statements


【解决方案1】:

你可以像这样使用 string.replace():

for i, row in df.iterrows():
    rating = float(row.Rating)
    price = float(row.Price.str.replace('$',''))
    if price >= 9:
        apps_morethan9 += 1

但您的实现可以在速度和复杂性方面得到改进:

print(df[df.Price.str.replace('$','').astype(float) >= 9].count().values[0])

【讨论】:

  • 感谢您的快速回复。真的很感激这个论坛太酷了。我尝试了使用 string.replace 建议的代码,但收到此错误消息 ``` apps_morethan = 0 for i, row in df.iterrows(): rating = row.Rating price = float(row.Price.replace('$' ,'') if price >= '9': apps_morethan += 1File "", line 7 if price >= '9': ^ SyntaxError: invalid syntax ``
  • 非常感谢。你们是最棒的。
  • 如果解决了您的问题,请用绿色钩子将答案标记为解决方案
【解决方案2】:

您可以在整个系列上应用 str.replace,然后像这样迭代它:

df["Price"].str.replace("$", "")
for i, row in df.iterrows():
    #rest of your routine

我建议您使用@gustavz 解决方案来提高性能

【讨论】:

  • 感谢您的帮助。非常感谢你们。
猜你喜欢
  • 2021-01-11
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 2023-03-08
  • 2020-12-31
  • 2017-10-01
  • 1970-01-01
相关资源
最近更新 更多