如何在pandas数据框列中将逗号作为千位分隔符插入?

16

我想要将美元金额列使用逗号分隔符进行格式化,以便更容易查看,但我还没有找到方法。有人可以告诉我应该怎么做吗?

import pandas as pd
df = pd.read_excel('filename.xlsx') 
df['Dollar Amount'].head()

Index  Dollar Amount
0      5721.48
1      4000.00
2      4769.00
3       824.07
4       643.60
5       620.00

Name: Dollar Amount, dtype: float64

这个回答解决了你的问题吗?如何使用逗号将数字格式化为千位分隔符 - Josiah Yoder
6个回答

21

请注意,它会将您的浮点类型转换为对象

df.DollarAmount.apply(lambda x : "{:,}".format(x))
Out[509]: 
0    5,721.48
1     4,000.0
2     4,769.0
3      824.07
4       643.6
5       620.0
Name: DollarAmount, dtype: object

2
谢谢。由于它是Pandas数据框,我不得不更改一件事情。df['Dollar Amount'].apply(lambda x : "{:,}".format(x)) - ACH
1
它是如何在正确的位置插入(,)的?你在哪里给出了位置? - Pyd
3
@pyd,你可以查看这个链接 :-) https://docs.python.org/3.4/library/string.html (搜索 {:,} 将会显示结果) - BENY
1
最新的文档链接:https://docs.python.org/3/library/string.html - Abraham Sangha
1
@user3423407 df.apply(lambda x : "{:,}".format(x),1)请将此代码翻译为中文: - BENY
显示剩余4条评论

9

这是一种更加简便易行的方法来获取千位分隔符。

df['Dollar Amount']=df['Dollar Amount'].apply('{:,}'.format)

2

这里有一个使用 locale 的解决方案,可以帮助你,只要你愿意将数字格式化为字符串:

import pandas as pd
import locale as lc

# Get the list of all locale options
all_locales = lc.locale_alias
# I'll use US conventions since that's what you mentioned in your question
lc.setlocale(lc.LC_ALL,all_locales["en_us"])

df = pd.DataFrame({"Dollar Amount":[1000, 2000000, 2500.01]})
df["Dollars Formatted"] = df["Dollar Amount"].apply(lambda x: "$"+lc.format("%.2f",x,True))

locale的方便之处在于,如果需要,您可以轻松地在不同的数字约定之间进行切换,并且它将继续应用这些约定来分隔百万和十亿。


2

使用map:

df['Dollar Amount'] = df['Dollar Amount'].map("{:,}".format)

您可以使用样式表,这样更加美观,并且可以在一行中完成所有的样式设置:

你也可以使用样式表,这样更好看,让你可以在一行中完成所有的样式设置:

df = df.style.format({'Dollar Amount': "{:,}"})

1
如果您需要在特定列中插入千位分隔符并删除小数点:
import pandas as pd
df = pd.DataFrame([(0.21, 1000.0), (0.01, 2000000.0), (0.66, 1000.0), (0.21, 330000.0)], columns=['A', 'B'])

之前:

      A          B
0  0.21     1000.0
1  0.01  2000000.0
2  0.66     1000.0
3  0.21   330000.0

对于“Col B”,插入逗号分隔符并删除小数点:对YOBEN_S上面的代码进行轻微调整,得到:

lst = list(df.columns)
lst.remove('A')
for c in lst:
    df[c] = df[c].astype(int).apply(lambda x: f'{x:,}')

之后:

      A          B
0  0.21      1,000
1  0.01  2,000,000
2  0.66      1,000
3  0.21    330,000

0

@Benny's answer 的 f 字符串版本:

df = pd.DataFrame({'DollarAmount': [5012.82, 1203, 4000.0, 824.07, 625.0]})
df.DollarAmount.apply(lambda x: f"{x:,}")

0    5,012.82
1     1,203.0
2     4,000.0
3      824.07
4       625.0
Name: DollarAmount, dtype: object

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接