3

Suppose I have a dataframe df as shown below

    qty
0   1.300
1   1.909

Now I want to extract only the integer portion of the qty column and the df should look like

   qty
0   1
1   1

Tried using df['qty'].round(0) but didn't get the desired result as it rounds of the number to the nearest integer.

Java has a function intValue() which does the desired operation. Is there a similar function in pandas ?

Gopal Chandak
  • 387
  • 7
  • 19

2 Answers2

6

Convert values to integers by Series.astype:

df['qty'] = df['qty'].astype(int)
print (df)
   qty
0    1
1    1

If not working above is possible use numpy.modf for extract values before .:

a, b = np.modf(df['qty'])
df['qty'] = b.astype(int)
print (df)
   qty
0    1
1    1

Or by split before ., but it should be slow if large DataFrame:

df['qty'] = b.astype(str).str.strip('.').str[0].astype(int)

Or use numpy.floor:

df['qty'] = np.floor(df['qty']).astype(int)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

You can use the method floordiv:

df['col'].floordiv(1).astype(int)

For example:

        col
0  9.748333
1  6.612708
2  2.888753
3  8.913470
4  2.354213

Output:

0    9
1    6
2    2
3    8
4    2
Name: col, dtype: int64
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73