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

我试图格式化美元金额栏有一个逗号分隔符为更容易查看,但我一直无法弄清楚。 有人可以告诉我的方式吗?

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 

注意它会将你的floattypes转换为object

 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 

这里有一个使用locale的解决scheme可能会有所帮助,只要您将数字格式化为string即可:

 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的便利之处在于,如果需要,您可以轻松地在不同的数字约定之间进行切换,并且会继续将这些约定用于数百万和数十亿个分隔符。