如何将 pandas 数据框的数据类型更改为具有定义格式的字符串?

2022-01-15 00:00:00 python pandas string floating-point format

问题描述

我开始为此扯头发 - 所以我希望有人能提供帮助.我有一个使用 openpyxl 从 Excel 电子表格创建的 pandas DataFrame.生成的 DataFrame 如下所示:

I'm starting to tear my hair out with this - so I hope someone can help. I have a pandas DataFrame that was created from an Excel spreadsheet using openpyxl. The resulting DataFrame looks like:

print image_name_data
     id           image_name
0  1001  1001_mar2014_report
1  1002  1002_mar2014_report
2  1003  1003_mar2014_report

[3 rows x 2 columns]

…具有以下数据类型:

print image_name_data.dtypes
id            float64
image_name     object
dtype: object

问题在于 id 列中的数字实际上是标识号,我需要将它们视为字符串.我尝试使用以下方法将 id 列转换为字符串:

The issue is that the numbers in the id column are, in fact, identification numbers and I need to treat them as strings. I've tried converting the id column to strings using:

image_name_data['id'] = image_name_data['id'].astype('str')

这看起来有点难看,但它确实产生了一个类型为object"而不是float64"的变量:

This seems a bit ugly but it does produce a variable of type 'object' rather than 'float64':

print image_name_data.dyptes
id            object
image_name    object
dtype: object

但是,创建的字符串有一个小数点,如图:

However, the strings that are created have a decimal point, as shown:

print image_name_data
       id           image_name
0  1001.0  1001_mar2014_report
1  1002.0  1002_mar2014_report
2  1003.0  1003_mar2014_report

[3 rows x 2 columns]

如何将 pandas DataFrame 中的 float64 列转换为具有给定格式的字符串(在本例中,例如 '%10.0f')?

How can I convert a float64 column in a pandas DataFrame to a string with a given format (in this case, for example, '%10.0f')?


解决方案

我无法重现您的问题,但您是否尝试过先将其转换为整数?

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

然后,关于您更一般的问题,您可以使用 map (在这个答案中).在你的情况下:

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

相关文章