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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47404472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:48:07  来源:igfitidea点击:

How to insert a comma as a thousands separator in a pandas dataframe column?

excelpandasdataframepython-3.6

提问by ACH

I'm trying to format the Dollar Amount column to have a comma thousands separator for easier viewing, but I haven't been able to figure it out. Can someone please show me the way?

我正在尝试将 Dollar Amount 列的格式设置为逗号千位分隔符以便于查看,但我一直无法弄清楚。有人可以给我指路吗?

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

采纳答案by YOBEN_S

Notice it will convert your floattype to object

请注意,它会将您的float类型转换为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

回答by madmapper

Here's a solution using localethat might help, as long as you're okay with formatting your numbers as strings:

这是一个使用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))

The convenient thing about localeis that you can easily change between different number conventions if you need to, and it will continue to apply those conventions for the millions and billions separators.

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

回答by Grant Shannon

If you need to insert thousands comma separators in a specific columnand remove the decimal place:

如果您需要在特定列中插入数千个逗号分隔符并删除小数位

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'])

Before:

前:

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

For "Col B" insert comma separators and remove decimal place: A slight adjustment to YOBEN_S'scode above gives:

对于“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:,}')

After:

后:

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