python - 如何自定义格式化 pandas 整数列以用逗号作为千位分隔符显示?
问题描述
我有一个数据框列GDP/year
,来自一个关于多年来自杀的数据集。此列的数据类型当前是对象(字符串),但我希望它为整数。
这些值是逗号分隔的,所以我不能直接将它们转换为整数。我尝试字符串删除逗号,存储为整数,然后我再次引入逗号,但它的类型恢复为对象。
数据集:https ://www.kaggle.com/russellyates88/suicide-rates-overview-1985-to-2016
# convert to int...
suicides[' gdp_for_year ($) '] = suicides[' gdp_for_year ($) '].str.replace(',','').astype(int)
# now reformat with commas as thousands separator...
suicides[' gdp_for_year ($) '] = suicides[' gdp_for_year ($) '].astype(int).apply(lambda x: "{:,}".format(x))
# ...wanted to get dtype integer, but it's back to object
解决方案
您正在将每个元素转换为字符串:"{:,}".format(x)
但我想你想在你的 pandas DataFrame 中显示你的数字以默认显示逗号分隔符,为此你可以这样做,但对于浮点数据类型:
pd.options.display.float_format = '{:,}'.format
如果您还想要 int 类型,则应该使用 monkey-patch pandas.io.formats.format.IntArrayFormatter
。
推荐阅读
- facebook - Facebook bot with Php (#100) 尝试访问节点类型(页面)上不存在的字段(消息)
- javascript - 从 Webpack 3 迁移到 Webpack 4 - babel-loader ReferenceError: Unknown plugin "syntax-dynamic-import"
- c++ - -lclsntsh 在与 oracle 程序的 c++ 连接中找不到
- android - 如何减少水平平面列表中项目之间的空间
- python-3.x - 为每个子文件夹制作字典
- amazon-web-services - 是一种提取 Amazon Kinesis firehose 中托管的服务使用的 IP 范围的方法吗?
- java - 如何防止 JpaRepository saveAndFlush 生成删除 sql 请求
- android - 将 MYSQL 连接到 Android Studio
- spring - 如何防止 null RequestParam 引发异常?
- docker - 在默认 docker-compose 网络上使用 internal: true 会导致 DNS 超时缓慢