ElkanaTheGreat
ElkanaTheGreat

Reputation: 91

Calculated column based on multiple columns

I am trying to create a new column in my pandas data frame based on the row-wise values in other columns.

I have tried using the apply method, but I don't fully understand how it works.

df = pd.DataFrame(data=['A', 'B', 'A'], columns=['Brand'])
Parameters = {'A': [0.3, 0.4], 'B': [0.1, 0.2]}

df['BrandMonthAdj1'] = df.apply(lambda x: Parameters[x['Brand']][0])

I expected this to return a column with 0.3 for the first and third row. and 0.1 for the second row. However I get the following error which I don't understand:

KeyError: ('Brand', u'occurred at index Brand')

Upvotes: 0

Views: 90

Answers (1)

BENY
BENY

Reputation: 323226

Using map then str slice

df.Brand.map(Parameters).str[0]
Out[11]: 
0    0.3
1    0.1
2    0.3
Name: Brand, dtype: float64
df['BrandMonthAdj1'] = df.Brand.map(Parameters).str[0]

Upvotes: 3

Related Questions