Rounding down values in Pandas dataframe column with NaNs

Viewed 30226

I have a Pandas dataframe that contains a column of float64 values:

tempDF = pd.DataFrame({ 'id': [12,12,12,12,45,45,45,51,51,51,51,51,51,76,76,76,91,91,91,91],
                        'measure': [3.2,4.2,6.8,5.6,3.1,4.8,8.8,3.0,1.9,2.1,2.4,3.5,4.2,5.2,4.3,3.6,5.2,7.1,6.5,7.3]})

I want to create a new column containing just the integer part. My first thought was to use .astype(int):

tempDF['int_measure'] = tempDF['measure'].astype(int)

This works fine but, as an extra complication, the column I have contains a missing value:

tempDF.ix[10,'measure'] = np.nan

This missing value causes the .astype(int) method to fail with:

ValueError: Cannot convert NA to integer

I thought I could round down the floats in the column of data. However, the .round(0) function will round to the nearest integer (higher or lower) rather than rounding down. I can't find a function equivalent to ".floor()" that will act on a column of a Pandas dataframe.

Any suggestions?

3 Answers

The answers here are pretty dated and as of pandas 0.25.2 (perhaps earlier) the error

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Which would be

df.iloc[:,0] = df.iloc[:,0].astype(int)

for one particular column.

Related