0

If the value in column 'y' is K, multiply the column 'x' values to 1e3. If column 'y' is M, multiply the column 'x' values to 1e6. Below code multiplies all the values to with 1e3

value_list = []
for i in list(result['x'].values):
    if np.where(result['y'] == 'K'):
        value_list.append(float(i)*1e3)
    elif  np.where(result['y'] == 'M'):
        value_list.append(float(i)*1e6)
    else:
        value_list.append(np.nan)
df['Value_numeric'] = value_list
df.head().Value_numeric

Dataframe: Result dataframe:

Output right now: Output right now:

sbl
  • 39
  • 8
  • Can you provide a [reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) with input data and your expected output? – Michael Szczesny Dec 30 '20 at 19:38
  • I have edited the question. column x has the amount. I need to convert it into same unit. – sbl Dec 30 '20 at 19:51
  • Please provide the expected [MRE](https://stackoverflow.com/help/minimal-reproducible-example). Show where the intermediate results deviate from the ones you expect. We should be able to paste a single block of your code into file, run it, and reproduce your problem. This also lets us test any suggestions in your context. Your posted code does not run. We also expect that you will trace the offending values just before the point of error. Where are you confused about how they got to those values? – Prune Dec 30 '20 at 19:51
  • [Include your data frame](https://stackoverflow.com/questions/52413246/how-to-provide-a-reproducible-copy-of-your-dataframe-with-to-clipboard) as part of the example. – Prune Dec 30 '20 at 19:52
  • Why are you doing this with a `for` loop and `if` checks instead of a simple broadcast command with conditional filters? – Prune Dec 30 '20 at 19:52
  • How can I do that? – sbl Dec 30 '20 at 19:55

2 Answers2

1

This case is simple enough that it's not necessary to use a loop or a custom function; one can use a simple assignment:

import pandas as pd
import numpy as np
d = {'x': [750, 5, 4, 240, 220], 'y': ['K', 'M', 'M', 'K', 'K']}

df = pd.DataFrame(data=d)

# here is the main operation:
df['value_numeric'] = np.where(df['y']=='K', df['x'] * 1e3, df['x'] * 1e6)
print(df)

output

     x  y  value_numeric
0  750  K       750000.0
1    5  M      5000000.0
2    4  M      4000000.0
3  240  K       240000.0
4  220  K       220000.0
ELinda
  • 2,658
  • 1
  • 10
  • 9
0

You can do something like this:

df = pd.DataFrame([[1,"a"],[2,'b'],[3,'c']], columns=['A', 'B'])

def calc(x):
    if x['B'] == 'a':
        return x['A'] * 10

    if x['B'] == 'b':
        return x['A'] * 20

    if x['B'] == 'c':
        return x['A'] * 30

df['calculate'] = df.apply(lambda x: calc(x),axis=1)

print(df)


#   A  B  calculate
#0  1  a         10
#1  2  b         40
#2  3  c         90

You can adjust your calculations as needed based on the condition.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
KJDII
  • 851
  • 4
  • 11