Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas astype int not removing decimal points from values

Tags:

python

pandas

I tried converting the values in some columns of a DataFrame of floats to integers by using round then astype. However, the values still contained decimal places. What is wrong with my code?

nums = np.arange(1, 11)
arr = np.array(nums)
arr = arr.reshape((2, 5))
df = pd.DataFrame(arr)
df += 0.1
df

Original df:

    0   1   2   3   4
0   1.1 2.1 3.1 4.1 5.1
1   6.1 7.1 8.1 9.1 10.1

Rounding then to int code:

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

Output:

    0   1   2   3   4
0   1.1 2.1 3.0 4.0 5.0
1   6.1 7.1 8.0 9.0 10.0

Expected output:

    0   1   2   3   4
0   1.1 2.1 3   4   5
1   6.1 7.1 8   9   10
like image 418
Daniel Poh Avatar asked Nov 05 '25 02:11

Daniel Poh


2 Answers

The problem is for the .iloc it assign the value and did not change the column type

l = df.columns[2:]
df[l] = df[l].astype(int)
df
     0    1  2  3   4
0  1.1  2.1  3  4   5
1  6.1  7.1  8  9  10
like image 89
BENY Avatar answered Nov 08 '25 01:11

BENY


One way to solve that is to use .convert_dtypes()

df.iloc[:, 2:] = df.iloc[:, 2:].round()
df = df.convert_dtypes()
print(df)

output:

     0    1  2  3   4
0  1.1  2.1  3  4   5
1  6.1  7.1  8  9  10

It will help you to coerce all dtypes of your dataframe to a better fit.

like image 38
Samuel Baptista Avatar answered Nov 08 '25 00:11

Samuel Baptista