to_dict() changes dtype from int32 to int64

Viewed 192

I am using

pd.testing.assert_frame_equal(expected,actual)

for unit testing,

expected = pd.Dataframe(actual.to_dict()) .

But pandas to_dict() function is implicitly changing the dtype from int32 to int64. How should I avoid it? Any help is highly appreciated.

1 Answers

to_dict isn't changing the dtype to int64.

to_dict returns a dict full of ordinary Python scalars, not NumPy or Pandas objects. An ordinary Python int has no dtype. When you call pandas.DataFrame again, pandas infers dtypes for all columns, and the inference has no information about the original dtypes.

You'll have to use something other than to_dict, or keep track of the original dtypes separately and fix them after reconstructing the dataframe.

Related