【问题标题】:How to insert a comma as a thousands separator in a pandas dataframe column?如何在熊猫数据框列中插入逗号作为千位分隔符?
【发布时间】:2018-05-04 09:46:55
【问题描述】:

我正在尝试将美元金额列格式化为使用逗号千位分隔符以便于查看,但我无法弄清楚。谁能给我指路?

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

【问题讨论】:

    标签: excel pandas dataframe python-3.6


    【解决方案1】:

    请注意,它会将您的 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
    

    【讨论】:

    • 谢谢。我不得不改变一件事,因为它是一个 Pandas 数据框。 df['Dollar Amount'].apply(lambda x : "{:,}".format(x))
    • @ACH 啊哈,你明白了 :-)
    • 它是如何在正确的位置插入 (,) 的?你在哪里提供职位?
    • @pyd 你可以查看链接 :-) docs.python.org/3.4/library/string.html (通过搜索 {:,} 你会看到结果)
    • @user3423407 df.apply(lambda x : "{:,}".format(x),1)
    【解决方案2】:

    这是获取千位分隔符的更可取的方法。

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        使用地图:

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

        您还可以使用更好的样式,让您在一行中完成所有样式:

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

        【讨论】:

          【解决方案5】:

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

          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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-09-23
            • 2020-10-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-20
            • 2010-12-21
            • 1970-01-01
            相关资源
            最近更新 更多