简体   繁体   English

在python中将价格格式从点(.)改为逗号(,)

[英]Change price format from dot (.) to Comma (,) in python

Iam using python's pandas dataframe to create a csv from a txt file.我正在使用 python 的 pandas 数据框从 txt 文件创建一个 csv。 This txt file has a price in dot format eg 23.45这个 txt 文件有一个点格式的价格,例如 23.45

In my csv I want the out in comma format, like 23,45.在我的 csv 中,我希望以逗号格式输出,例如 23,45。

I tried the following but failed to achieve the end result:我尝试了以下但未能达到最终结果:

  1. Replace the particular column's (.) to (,) -> Result: Whole numbers is gone, new cell has value "None".将特定列的 (.) 替换为 (,) -> 结果:整数消失了,新单元格的值为“无”。
  2. Try locale for EUR but got a currency sign € at the end.尝试使用 EUR 的语言环境,但最后得到了货币符号 €。 Which i couldnt found a way to remove too.我也找不到删除的方法。
  3. Tried Lambda function to format.尝试使用 Lambda 函数进行格式化。 Still didn't achieved the result.结果还是没有达到。

Below are the tried methods I used.以下是我使用过的尝试过的方法。

 1. df['price'] = df['price'].replace('.',',', inplace= True)
 2. locale.setlocale(locale.LC_MONETARY, 'de_DE')
   df['price'] = df['price'].apply(locale.currency)
 3. df['price'] = df['price'].apply(lambda y: '{:.,2f}'.format(y))

Please help me out where I was missing.请帮我找出我失踪的地方。

Try this, You almost got it.试试这个,你几乎明白了。 Just had to convert the float to str and then apply str.replace .只需将float转换为str然后应用str.replace

df['price'] = df['price'].astype(str).str.replace('.',',')

Input:输入:

   price
0  20.12
1  10.12
2  34.12
3  35.43

Output (After running the code)输出(运行代码后)

   price
0  20,12
1  10,12
2  34,12
3  35,43

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM