daiyue
daiyue

Reputation: 7448

pandas converts float64 to int

I am trying to convert the dtype of a column (A) in a dataframe from float64 to int,

df['A'].astype(numpy.int64)

but after that, A still gets float64 as dtype. I am wondering how to resolve the issue.

Upvotes: 2

Views: 10689

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210822

If you have NaN values, then Pandas can't convert it to int.

But most probably you just didn't assign result back to A column (as @jezrael has already said).

If you would try to convert NaN's to integer you would get the following exception:

In [4]: df = pd.DataFrame({'A':[1,2,np.nan,4]})

In [5]: df
Out[5]:
     A
0  1.0
1  2.0
2  NaN
3  4.0

In [6]: df['A'] = df['A'].astype(np.int64)
...
skipped
...
ValueError: Cannot convert non-finite values (NA or inf) to integer

Upvotes: 1

jezrael
jezrael

Reputation: 862441

It seems your output is not assign back, so need:

df['A'] = df['A'].astype(numpy.int64)

If NaNs use fillna for convert them to int:

df['A'] = df['A'].fillna(0).astype(numpy.int64)

Or remove all rows with NaNs in A column by dropna:

df = df.dropna('A')
df['A'] = df['A'].astype(numpy.int64)

Upvotes: 6

Related Questions