我开始为此扯头发 - 所以我希望有人能提供帮助.我有一个使用 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 数据框的数据类型更改为具有定义格式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何制作一个在 Python 中提供角色的不和谐机器人How to make a discord bot that gives roles in Python?(如何制作一个在 Python 中提供角色的不和谐机器人?)
Discord 机器人没有响应命令Discord bot isn#39;t responding to commands(Discord 机器人没有响应命令)
你能得到“关于我"吗?Discord 机器人的功能?Can you Get the quot;About mequot; feature on Discord bot#39;s? (Discord.py)(你能得到“关于我吗?Discord 机器人的功能?(不和谐.py))
message.channel.id Discord PYmessage.channel.id Discord PY(message.channel.id Discord PY)
如何在 heroku 上托管我的 discord.py 机器人?How do I host my discord.py bot on heroku?(如何在 heroku 上托管我的 discord.py 机器人?)
discord.py - 自动更改角色颜色discord.py - Automaticaly Change an Role Color(discord.py - 自动更改角色颜色)