pandas 熊猫格式列作为货币
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35019156/
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
Pandas format column as currency
提问by Dance Party2
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 .3K
1 B .5K
2 C df['C'] = df['C'].apply(lambda x: "${:.1f}k".format((x/1000)))
.6K
3 D .0K
The second thing I need to do is somehow get these into a Seaborn heat map, which only accepts floats and integers. See herefor more on the heat map aspect.
我需要做的第二件事是以某种方式将这些放入 Seaborn 热图,它只接受浮点数和整数。有关热图方面的更多信息,请参见此处。
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!
提前致谢!
回答by Jace Whitmer
Or you could use a lambda function for shorter syntax
或者您可以使用 lambda 函数来缩短语法
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)