To cast a column to integer in Pandas, you can use the astype() method. Here’s an example:
import pandas as pd # Create a sample DataFrame df = pd.DataFrame({'numbers': ['1', '2', '3', '4', '5']}) # Cast the 'numbers' column to integer using astype() df['numbers'] = df['numbers'].astype(int) # Print the DataFrame print(df)
In the example above, the astype() method is used to convert the ‘numbers’ column to integer. The method takes the data type to which you want to convert the column as an argument. In this case, we passed int as the argument to convert the ‘numbers’ column to integers.
Note that if there are any non-integer values in the column, the astype() method will raise a ValueError. In this case, you will need to clean your data to remove or replace those non-integer values before casting to int.
1 thought on “How to cast column to int in Pandas”