stackq
stackq

Reputation: 491

Converting float64 to integer

I want to convert a float64 column to integer.

print(df.sales.dtype)
print(df.sales)

float64
0        4.000
1        6.454
2        5.654
3       23.463

print(df.sales.fillna(0).astpye('int64'))

0        4
1        6
2        5
3       23

Whereas I am expecting 4000, 6454, 5654, 23463. The column can contain empty data that's why I use fillna(). How come astype() isn't working as expected?

Upvotes: 0

Views: 1503

Answers (2)

I'mahdi
I'mahdi

Reputation: 24049

try this:

df = pd.DataFrame({'sales': {0: 4.000, 1: 6.454, 2: float('nan'), 3:23.463, 4:5.654}})

df = (df.sales.fillna(0)*1000).astype(int)
#OR
df = (df.sales.fillna(0)*1000).astype(np.int64)

print(df)

output:

0     4000
1     6454
2        0
3    23463
4     5654
Name: sales, dtype: int64

EDIT: if you want converting currency with $ to int64 you can try this:

df = pd.DataFrame({'sales': {0: '$4.000', 1: '$6.454', 2: float('nan'), 3: '$23.463', 4:'$5.654'}})

print(df)

df['sales'] = (((df['sales'].replace('[\$,]', '', regex=True).astype(float)).fillna(0))*1000).astype(np.int64) 

print();print(df)

output:

     sales
0   $4.000
1   $6.454
2      NaN
3  $23.463
4   $5.654

   sales
0   4000
1   6454
2      0
3  23463
4   5654

Upvotes: 1

Jon Nir
Jon Nir

Reputation: 585

Based on your comments and if I understand correctly, you want:

  1. to fill empty values with 0.
  2. to multiply the entire series by 1000.
  3. to cast the result as int64.

Did I understand you correctly?

(df.sales.fillna(0) * 1000).astype(int64)

Upvotes: 0

Related Questions