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

前端 未结 5 1626
北恋
北恋 2020-12-10 06:53

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

5条回答
  •  旧时难觅i
    2020-12-10 07:38

    If you need to insert thousands comma separators in a specific column and 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's code above gives:

    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
    

提交回复
热议问题