piRSquared piRSquared - 28 days ago 5
Python Question

downcasting series or dataframe element by element

consider the

pd.DataFrame
df


df = pd.DataFrame([
[1.0, 1.5],
[2.2, 3.0]
])





I want to downcast the individual elements to int if they are equal. I understand that each column will end up as object type. That's OK.

enter image description here

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 2 columns):
0 2 non-null object
1 2 non-null object
dtypes: object(2)
memory usage: 112.0+ bytes

Answer

You need to convert the dtype to object first, then you can use a mask to overwrite the values of interest using astype(int) on the df assuming all columns are numeric:

In [120]:
df = df.astype(object)
df[df == df.astype(int)] = df.astype(int)
df

Out[120]:
     0    1
0    1  1.5
1  2.2    3

Without the cast the assignment stays as float

You can see that the individual types are changed:

In [123]:
df.applymap(type)

Out[123]:
                 0                1
0    <class 'int'>  <class 'float'>
1  <class 'float'>    <class 'int'>