【问题标题】:How to remove all string or numbers after certain Character in Pandas?如何删除熊猫中某些字符后的所有字符串或数字?
【发布时间】:2021-02-16 04:58:38
【问题描述】:

晚上好,我一直在搜索运动鞋区的亚马逊网站。

现在我得到两个范围内的价格,即 1100 - 2300

如何删除 Pandas 中从 - 到结尾的所有内容以及货币符号。这是我尝试过的以及我各自的输出

csv 文件

https://easyupload.io/ayaivg

import pandas as pd

Azs = pd.read_csv("amazsneakers.csv")

Azs['Price'].str.replace("-","")

输出:

【问题讨论】:

  • 您也可以添加示例输入吗?
  • 嗨,你是指 csv 文件吗??
  • Azs['Price'].astype(str).apply(lambda x: x.split("-")[0])
  • 嗨,我在应用后出现错误。 'StringMethods' 对象没有属性 'apply'
  • @Firaki12345,不是 CSV 文件,但几行 (3-5) 就足够了。

标签: python python-3.x pandas jupyter-notebook


【解决方案1】:

您可以使用Series.str.split 进行空格分割,然后选择第二个分割值,删除, 并转换为数字:

Azs = pd.read_csv("amazsneakers.csv")

Azs['Price'] = Azs['Price'].str.split().str[1].str.replace(',','').astype(float)

或者先删除,,然后通过Series.str.extract提取浮点数:

Azs['Price'] = Azs['Price'].str.replace(',','').str.extract('(\d+\.\d+)').astype(float)

print (Azs['Price'])

0      645.0
1      655.0
2      799.0
3      799.0
4      849.0
 
169    367.0
170    199.0
171    386.0
172    499.0
173    401.0
Name: Price, Length: 174, dtype: float64

【讨论】:

  • 嗨,我刚刚用上面的 lambda 函数做了。谢谢:)
【解决方案2】:

请试试这个 -

test_string = "ab-cd"

split_string = test_string.split("-", 1)

#Split into "ab" and "cd"

required_string = split_string[0]

print(required_string)

【讨论】:

    【解决方案3】:

    Azs['Price'] = Azs['Price'].apply(lambda x: x.split(".")[0])

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多