Chuck Carlson
Chuck Carlson

Reputation: 987

Appending row to empty DataFrame converts dtype from int to object

I am attempting to add a series consisting of ints to a dataframe, but the items in the dataframe get converted to objects, instead of ints.

How can I keep the dtype as int for the items in the dataframe.

Here is some demo code:

>>> import pandas as pd
>>> df = pd.DataFrame(columns =['a','b','c'],  dtype=int)
>>> row = pd.Series(0,['a','b','c'],dtype=int)
>>> row = row.rename('row')
>>> print(row)
a    0
b    0
c    0
Name: row, dtype: int64
>>> df.append(row)['a']
row    0
Name: a, dtype: object
>>> 

Upvotes: 1

Views: 328

Answers (1)

piRSquared
piRSquared

Reputation: 294258

dtype=int apparently doesn't stick when you initiate the dataframe with no data.

Workround

df = pd.DataFrame(columns=['a','b','c']).astype(int)
row = pd.Series(0, ['a', 'b', 'c'], dtype=int, name='row')

df.append(row).dtypes

a    int64
b    int64
c    int64
dtype: object

Upvotes: 1

Related Questions