如何在python中将列中的“,”替换为字符串(例如“58,00”)和“.”(如在excel中查找和替换)?

2024-09-26 22:08:51 发布

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

我想对我的银行数据有更多的了解。我想查看每个类别的总金额,但我似乎无法对数据集中的金额进行浮动。你知道吗

我已经将数据(csv文件)上传到一个数据帧(bank)中,看起来像这样:

 date        amount   category
 2018-09-01  -58,00   dinner 
 2018-09-02  -60,00   grocery
 2018-09-02  -115,00  clothing

我试过使用.replace和.astype(float),两者都不起作用

#I've tried this formula, but it doesn't work (the x-values even get shuffled??): 

#replace ',' with '.' in amount:
def komma(x):
    for x in bank['amount']:
        x = list(set(x))
        for a in x:
            if a == ',':
                a.replace(",",".")
    return "".join(x)

komma(x)
bank.head()

#my result with .replace(',','.') is no changes in the dataframe 
#my result with .astype(float) was 
#ValueError: could not convert string to float: '-58,00'

Tags: the数据informywith银行result
2条回答

你可以试试这个:

df["amount"]=df["amount"].apply(lambda x: x.replace(',','.'))

但是,将“,”转换为“.”之后再转换为float可能会导致数据精度损失。你知道吗

         date  amount  category
0  2018-09-01   -58.0    dinner
1  2018-09-02   -60.0   grocery
2  2018-09-02  -115.0  clothing

试试这个:

df["amount"]=df["amount"].str.replace(",", ".").astype(float)

(不需要任何for循环)

相关问题 更多 >

    热门问题