如何从Pandas系列中的字符串中删除“$”符号?

2024-04-23 16:05:06 发布

您现在位置:Python中文网/ 问答频道 /正文

急需帮助。我试图有条件地迭代Google play store csv文件的行。我一直在谈论熊猫不认识“>;=”的问题由于某种原因,我的一些循环中出现了符号。也就是说,使用条件“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'``` 


Tags: appscsvingtdfforif符号
2条回答

可以使用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])

在迭代之前,可以对整个系列应用str.replace,如下所示:

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

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

相关问题 更多 >