user2896120
user2896120

Reputation: 3282

Converting number to decimal when given both

I have 2 columns: price and dec. As shown in this sample dataframe:

price  dec
505    2
300    2
680    3
100    2

What I'd like to do is make another column that takes the price and decimal and then converts it like so:

price  dec  realprice
505    2    5.05
300    2    3.00
680    3    .680
100    2    1.00

How do I make a function that does this?

Upvotes: 2

Views: 52

Answers (2)

rahlf23
rahlf23

Reputation: 9019

Just divide the columns and use powers of 10:

df['realprice'] = df['price']/(10**df['dec'])

Yields:

   price  dec  realprice
0    505    2       5.05
1    300    2       3.00
2    680    3       0.68
3    100    2       1.00

Upvotes: 1

BENY
BENY

Reputation: 323396

Using div with **

df.price.div(10**df.dec)
Out[510]: 
0    5.05
1    3.00
2    0.68
3    1.00
dtype: float64

Upvotes: 6

Related Questions