0

I am trying to find a shortcut to assigning a pandas series from elements in a list.

My code:

import pandas as pd
df=pd.DataFrame([[1,2,2183],[1,4,2235],[2,3,6123],[3,4,4213]],columns=['month','staff','sales'])

goals=[1346,4456,4574]

df['goals']=goals[df['month']-1]

The last line throws an error: TypeError: list indices must be integers or slices, not Series

Desired output looks like this:

   month  staff  sales  goals
0      1      2   2183   1346
1      1      4   2235   1346
2      2      3   6123   4456
3      3      3   4213   4574

This is a general case, and in the future, the goals array might actually be multidimensional.

3
  • what about: df['goals']=goals? Commented Nov 28, 2017 at 17:33
  • 1
    I gave a simple example. In reality, there might be a number of months that need to be looked up and not in order in the Pandas series. Goals will always be in order. Commented Nov 28, 2017 at 17:34
  • Great question, thank you! Commented Nov 15, 2018 at 6:32

2 Answers 2

3
In [80]: mapping = pd.Series(goals, index=df.month.unique())

In [81]: mapping
Out[81]:
1    1346
2    4456
3    4574
dtype: int64

In [82]: df['goals'] = df.month.map(mapping)

In [83]: df
Out[83]:
   month  staff  sales  goals
0      1      2   2183   1346
1      1      4   2235   1346
2      2      3   6123   4456
3      3      4   4213   4574
Sign up to request clarification or add additional context in comments.

4 Comments

Can this work for goals determined by month and staff#? A matrix of goals?
@hrschbck, i don't understand - what is matrix of goals?
If the goal depended on both the month and the staff#, if Goal(month=1,staff=2)=1500 and Goal(month=1,staff=4)=1346?
@hrschbck, please ask a new question and provide there a corresponding data sets (input and output)...
1
import numpy as np

First, a dictionary of values for goals and their respective months:

goals_dict = dict(zip(np.arange(1,len(goals)+1), goals))

Now use map

df['goals'] = df.month.map(goals_dict)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.