Pandas format column as currency

流过昼夜 提交于 2020-03-20 01:25:50

问题


Given the following data frame:

import pandas as pd
df = pd.DataFrame(
        {'A':['A','B','C','D'],
         'C':[12355.00,12555.67,640.00,7000]
        })
df

    A   C
0   A   12355.00
1   B   12555.67
2   C   640.00
3   D   7000.00

I'd like to convert the values to dollars in thousands of USD like this:

    A   C
0   A   $12.3K
1   B   $12.5K
2   C    $0.6K
3   D    $7.0K

The second thing I need to do is somehow get these into a Seaborn heat map, which only accepts floats and integers. See here for more on the heat map aspect.

I'm assuming once the floats are converted to currency, they will be in object format but I'm hoping there's a way around that.

Thanks in advance!


回答1:


    def format(x):
        return "${:.1f}K".format(x/1000)


    df = pd.DataFrame(
        {'A':['A','B','C','D'],
         'C':[12355.00,12555.67,640.00,7000]
        })

    df['C'] = df['C'].apply(format)

    print(df)



回答2:


Or you could use a lambda function for shorter syntax

df['C'] = df['C'].apply(lambda x: "${:.1f}k".format((x/1000)))


来源:https://stackoverflow.com/questions/35019156/pandas-format-column-as-currency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!