Skip to main content
 首页 » 编程设计

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

2024年11月24日28虾米姐

我是 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