【问题标题】:Converting a full column of integer into string with thousands separated using comma in pandas将整列整数转换为字符串,在 Pandas 中使用逗号分隔千位
【发布时间】:2017-05-09 22:40:07
【问题描述】:

假设我使用 python 中的 pandas 将人口数据存储在数据框的列中,并将国家名称作为行索引。如何使用逗号将整列数字转换为字符串千位分隔符。 基本上,我需要12345678,整数,转换成12,345,678。

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    使用apply 格式化数字。

    In [40]: ps.apply('{:,}'.format)
    Out[40]:
    CountryA    12,345,678
    CountryB     3,242,342
    dtype: object
    
    In [41]: ps
    Out[41]:
    CountryA    12345678
    CountryB     3242342
    dtype: int64
    

    【讨论】:

    • 这可能吗 --> 778123232232 --> 77,81,23,323,232 ?
    • 您可以通过locale.setlocale(locale.LC_NUMERIC, "en_IN") 做到这一点,请参阅stackoverflow.com/a/14238258
    • @MohammadYusufGhazi 你从哪里得到的数据
    • 这是默认设置 - docs.python.org/3/library/… - 使用逗号作为千位分隔符 - '{:,}'.format(1234567890) == '1,234,567,890'
    【解决方案2】:

    您也可以使用正则表达式。

    df['Population'].str.replace(r"(?!^)(?=(?:\d{3})+$)", ",")
    

    查看演示。

    https://regex101.com/r/cVYAGw/1

    【讨论】:

    • 注意:如果 Population 是任何其他类型,则必须转换类型。 df['Population'].astype(str).str.replace..
    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多