0

I was trying to multiply a column in pandas df but i didnt get the expected results: for exemple i have a value which is 22 and i want to convert it to 22000 ...

i tried both these codes and both gave me same incorrect value

k['prix_millions'] = k['prix'].apply(lambda x: x * 1000 if int(x) == x and len(str(x)) == 2 else x)

also this:

def to_md(x):
    if len(str(x)) == 2:
        return x * 1000
    else:
        return x

# create a new column called prix_millions
k['prix_millions'] = k['prix'].apply(to_md)

i want to multiply the values in 1000

desertnaut
  • 57,590
  • 26
  • 140
  • 166
kim seol
  • 15
  • 2

1 Answers1

1

Assuming from your code that you want to multiply by 1000 if the value is > 10 and < 100 (2 digits), and an integer:

# does the value have 2 digits?
m1 = k['prix'].between(10, 100, inclusive='left')
# is it an integer?
m2 = k['prix'].round().eq(k['prix'])

# then multiply by 1000 and assign to a new column
k['prix_millions'] = k['prix'].mask(m1 & m2, 1000*k['prix'])

# or with numpy
# import numpy as np
# k['prix_millions'] = k['prix'].mul(np.where(m1&m2, 1000, 1))

With your original string logic, you could also have used: m1 = k['prix'].astype(str).str.len().eq(2).

mozway
  • 194,879
  • 13
  • 39
  • 75
  • "How to do X in Pandas based on condition" is probably the most asked Python question on this site. It's kind of fascinating. – ddejohn Mar 27 '23 at 18:43
  • 1
    @ddejohn this, pivot, melt, groupby.sum, cumcount, and combinations/variant of those… We should have a checklist of canonicals to read before being able to ask a question ;) – mozway Mar 27 '23 at 18:48
  • I do have a macro for this thread: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – ddejohn Mar 27 '23 at 20:05