How do I change data-type of pandas data frame to string with a defined format?(如何将 pandas 数据框的数据类型更改为具有定义格式的字符串?)
问题描述
我开始为此扯头发 - 所以我希望有人能提供帮助.我有一个使用 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)
这篇关于如何将 pandas 数据框的数据类型更改为具有定义格式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 pandas 数据框的数据类型更改为具有定义格式的字符串?
基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
