Anwar San
Anwar San

Reputation: 81

ValueError: invalid literal for int() with base 10: ' ' when convert type of data

I am changing data type in python. First, my dataset look like: enter image description here

I checked the dataset type of each column:

#Output: enter image description here

Then when I want to convert the dataset with this code:

df_tr = df1_dlq_slice.replace({'C': -1, 'F': -2, 'Z': -3}).astype(int).T
df_tr.head()

ValueError: invalid literal for int() with base 10: ' ' happened.

Upvotes: 1

Views: 115

Answers (1)

jezrael
jezrael

Reputation: 862511

First idea is replace also empty strings (and all another values):

df_tr = df1_dlq_slice.replace({'C': -1, 'F': -2, 'Z': -3,'':0}).astype(int).T

Or if need convert all another values to 0 after replace use:

df_tr = (df1_dlq_slice.replace({'C': -1, 'F': -2, 'Z': -3})
                      .apply(pd.to_numeric, errors='coerce')
                      .fillna(0)
                      .astype(int)
                      .T)

For test problematic values use:

df1 = df1_dlq_slice.replace({'C': -1, 'F': -2, 'Z': -3})

s = df1.stack()
L = s[pd.to_numeric(s, errors='coerce').isna()].unique().tolist()
print (L)

Upvotes: 2

Related Questions