問題描述
我開始為此扯頭發 - 所以我希望有人能提供幫助.我有一個使用 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模板網!