0

I am creating a dataframe that has an ID Code that needs to be a string, but is often a string representation of an integer. Pandas seems to automatically convert this from the data type str to the data type int after saving the dataframe to csv and then reading the dataframe back from csv as per the below example:

import pandas as pd

df = pd.DataFrame({'Fruit':['Apple','Orange','Banana'],'ID Code':['121','122','123']},index=[0,1,2])

This gives:

    Fruit   ID Code
0   Apple   121
1   Orange  122
2   Banana  123

As per below the dtype of the ID Code column is an object and the ID Codes themselves are of the dtype str:

df.info()

>>>

<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 0 to 2
Data columns (total 2 columns):
 #   Column   Non-Null Count  Dtype 
---  ------   --------------  ----- 
 0   Fruit    3 non-null      object
 1   ID Code  3 non-null      object
dtypes: object(2)
memory usage: 72.0+ bytes

print(df['ID Code'][0],type(df['ID Code'][0]))

>>>

121 <class 'str'>

Then I want to save the dataframe to file for reference later.

df.to_csv('fruits.csv')

Then I want to reload the file, but with the ID Code as the index column AND for the index column to be/remain as strings rather than emerge as integers (as seems to be the default behaviour).

df = pd.read_csv('fruits.csv',index_col='ID Code')
df

>>>

ID Code Unnamed: 0  Fruit
121     0           Apple
122     1           Orange
123     2           Banana

However, the ID Code column has now converted to dtype int.

print(df.index[0],type(df.index[0]))

>>>

121 <class 'numpy.int64'>

Ideally, I want to reload the dataframe with the index specified as dtype str at the time of loading. However, if this is not possible, what is the most efficient and pythonic way to realod the dataframe and achieve the ID Code, now the index, reloading as dtype str.

Thanks!

Update:

This is one solution after reading the .csv into the dataframe:

df.index = df.index.astype(str)

>>>

print(df.index[0],type(df.index[0]))

but is there any way of specifying this dtype for the index at the time of reading the .csv into the dataframe? Thanks!

1
  • you could add the dtypes information to the dataframe and save it as csv; then when you read the csv, you could use the dtypes info to build the original dataframe back.
    – user7864386
    Feb 23, 2022 at 4:29

1 Answer 1

0

Why exactly do you want your indexes that are integers to be strings? I have never tried to do this with indexes but instead of .astype() try the method to_string().

2
  • Perhaps this is better as a comment on the original post? In any case, the reason I want them to be strings is that sometimes the ID Codes will be alpha numeric and I need a consistent dtype across all references to the ID Code.
    – agftrading
    Feb 22, 2022 at 22:58
  • I can't post a comment yet. Based on my google searches I think you'll have to do deal with the dtype everytime.
    – luka1156
    Feb 23, 2022 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.