Python ProgrammingPython Programming

Convert floats to ints in Pandas DataFrame?

Alter column data type from Float64 to Int32:

import pandas as pd

df = pd.DataFrame({'DailyExp': [75.7, 56.69, 55.69, 96.5, 84.9, 110.5,
                                58.9],
                   'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean',
                         'Christina', 'Cornelia'])

print("\n----------------Before---------------\n")
print(df.dtypes)
print(df)

df['DailyExp'] = df['DailyExp'].astype(int)

print("\n----------------After----------------\n")
print(df.dtypes)
print(df)


C:\python\pandas examples>python example18.py
 
----------------Before---------------
 
DailyExp    float64
State        object
dtype: object
           DailyExp State
Jane          75.70    NY
Nick          56.69    TX
Aaron         55.69    FL
Penelope      96.50    AL
Dean          84.90    AK
Christina    110.50    TX
Cornelia      58.90    TX
 
----------------After----------------
 
DailyExp     int32
State       object
dtype: object
           DailyExp State
Jane             75    NY
Nick             56    TX
Aaron            55    FL
Penelope         96    AL
Dean             84    AK
Christina       110    TX
Cornelia         58    TX
 
C:\python\pandas examples>