gpt4 book ai didi

python - 从字符串中提取数值并保存到数据框时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:56 25 4
gpt4 key购买 nike

我是 Python 的新手,之前发布了我的问题并收到了其他人的建议,但仍然无法解决我的问题。我正在重新发布我的帖子,并进行了一些修改,并结合了其他人的建议。我不仅是 Python 的新手,而且在表达我的问题时也遇到了问题。

我想将所有价格从字符串转换为数字,例如从“3K”转换为“3000”以保持数据分析的一致性。目前,K表示千就足够了,不需要进入百万或数十亿。

这是在 Python 数据框架上完成的,我仍然不熟悉迭代、列表和遇到我不理解的错误。

a) 我无法将字符串转换为 float 。 “ValueError:无法将字符串转换为 float :”

b) 然后我决定转换为字符串,但我无法将其作为字符串存储在数据框中。我的输出是空单元格。

import pandas as pd
import numpy as np
import re

def regex_filter(val):
new_price = val
if val:
price = ' '
mo = re.search('\d+[kK]',val)
if mo:
price = str(price).replace('K','000')
print("The New value is ",price)
new_price = price
return new_price
else:
return new_price
else:
return new_price


if __name__ == "__main__":

df = pd.read_csv('ProductID_price.csv', encoding='utf8')
df['price'] = df['price'].apply(regex_filter)

输入

    product_id  product_name                        price
0 1 Mares XR Kevlar Diving Dry Suit 3K
1 2 Beuchat Abyss Dry Diving Dry Suit 2050
2 3 Typhoon Scuba Dive Dry Suit 1.5K
3 4 Scubapro Evertech Drysuit Men 4,059.99

输出

    product_id  product_name                        price
0 1 Mares XR Kevlar Diving Dry Suit
1 2 Beuchat Abyss Dry Diving Dry Suit 2050
2 3 Typhoon Scuba Dive Dry Suit
3 4 Scubapro Evertech Drysuit Men 4,059.99

最佳答案

我会这样做:

def conv(s, conv_from="K", conv_to=1000):
return s.mask(
s.str.contains(f"\d+{conv_from}", na=False),
pd.to_numeric(s.str.replace(conv_from,""),
errors="coerce") * conv_to,
errors="ignore")

# get rid of commas and spaces
df["price"] = df["price"].str.replace(r"[\s,]", "")

df["price"] = df["price"].pipe(conv, "[Kk]", 10**3).pipe(conv, "[Mm]", 10**6)

例子:

In [96]: df
Out[96]:
price
0 3K
1 0.56M
2 2050
3 1.5K
4 4,059.99

解决方法:

In [97]: df["price"] = df["price"].str.replace(r"[\s,]", "")

In [98]: df["price"] = df["price"].pipe(conv, "[Kk]", 10**3).pipe(conv, "[Mm]", 10**6)

结果:

In [99]: df
Out[99]:
price
0 3000
1 560000
2 2050
3 1500
4 4059.99

关于python - 从字符串中提取数值并保存到数据框时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56504338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com