How to save csv file in python with datatype of one particular columns has to be int32?

Viewed 137

I am saving the dataframe df after converting a column to data type np.int32. However, when I load it back in, I find the data type is np.int64. How can I fix this?

# creating a dictionary 
dict = {'Id':[1, 2, 3, 4],
        'Name':['John', 'Rahul', 'Jaspreet', 'Watson']}

##.....................................................

df = pd.DataFrame(dict)
print(df)

# output::
#       Id  Name
# 0     1   John
# 1     2   Rahul
# 2     3   Jaspreet
# 3     4   Watson

df['Id']=df['Id'].values.astype(np.int32)
df['Id'].dtype
# output  :  dtype('int32')

df.to_csv('Justtry.csv',index=False)

df1 = pd.read_csv('Justtry.csv')
df1['Id'].dtype
# output: dtype('int64')
1 Answers

when you read the csv, you can set the argument to int32

data = pd.read_csv(..., dtype={'Id': np.int32})
Related