1

Currently trying to change some market values in a dataframe if some value is present in another column. I'm only familiar with list comprehension for creating new columns, but im not sure its possible to do it this way.

I tried the following function, though it doesn't work:


def multiply_with(x):
    if df['a'] in list_multiple_double: 
        x = x * 0.5
    elif df['a'] in list_multiple_triple:  
        x = x * 0.33
    else: 
        x = x
    return x

I tried applying this on the market value column, but no luck.

Assume there are two columns a and b in a pd.dataframe, and i would like to create c. Also assume 2 lists, list_a and list_b. For every observation, if a is present in list_a then multiply by 0.5 and return this in column c. If a is present in list_b then multiply by 0.333 and return in c. If not present either return a in c. I need the following:

list_a = ['Denmark Sweden', 'Norway Sweden']
list_b = ['Denmark Sweden Norway']


values = [200,300,500,1000,200]
country = ['Denmark', 'Denmark Sweden', 'Denmark Sweden Norway', 'Sweden', 'Norway']
values_adj = [200, 150, 166.67, 1000, 200]

df = pd.DataFrame()
df['values'] = pd.Series(values)
df['country'] = pd.Series(country)
df['values_adj'] = pd.Series(values_adj)
Sociopath
  • 13,068
  • 19
  • 47
  • 75
Phils19
  • 156
  • 2
  • 8
  • 3
    please add a sample data and final expected output with your explanation. thanks – anky Mar 23 '19 at 13:14
  • What happens when it's just Denmark? Would it return just the same value without multiplication? – Mohit Motwani Mar 23 '19 at 13:27
  • Possible duplicate of [Create Column with ELIF in Pandas](https://stackoverflow.com/questions/18194404/create-column-with-elif-in-pandas) – ALollz Mar 23 '19 at 16:54

2 Answers2

2
df['values_adj'] = df['values']
df.loc[df['country'].isin(list_a), 'values_adj'] *= 0.5
df.loc[df['country'].isin(list_b), 'values_adj'] *= 0.33
mujjiga
  • 16,186
  • 2
  • 33
  • 51
2

Use np.select:

df['values_adj'] = np.select([df['country'].isin(list_a), df['country'].isin(list_b)], [df['values']*0.5, df['values']*0.333], df['values'])

print(df)

Output:

values                country  values_adj
0     200                Denmark       200.0
1     300         Denmark Sweden       150.0
2     500  Denmark Sweden Norway       166.5
3    1000                 Sweden      1000.0
4     200                 Norway       200.0
Sociopath
  • 13,068
  • 19
  • 47
  • 75