'Having Pandas astype give type conditionally

I have a column within my dataframe for each month that contains numbers unless there's an invalid value, in which case it shows a text error.

Using df.astype({'Jan':'int32'}).dtypes fails because of the text error within the Jan column.

Is there a way to export the dataframe to Excel with the numeric data as int32, while not yielding an error because of the text?

Thanks!



Solution 1:[1]

You can drop or replace the text values and then convert normally.

An example with pandas.DataFrame.loc to drop the values:

df = df.loc[df['Jan'].str.isnumeric()]
df.astype({'Jan': 'int32'}).dtypes

Or to replace:

df.loc[~df['Jan'].str.isnumeric(), ['Jan']] = 0
df.astype({'Jan': 'int32'}).dtypes

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad Ayoub