fred.schwartz
fred.schwartz

Reputation: 2155

Map Dictionary Values to pandas column

I have a dictionary

dates={'Jan': [1, 1],
 'Feb': [1, 1],
 'Mar': [1, 1],
 'Apr': [2, 1],
 'May': [2, 1],
 'Jun': [2, 1],
 'Jul': [3, 2],
 'Aug': [3, 2],
 'Sep': [3, 2],
 'Oct': [4, 2],
 'Nov': [4, 2],
 'Dec': [4, 2]}

I also have a dataframe with months in

   Month
0   Jan
1   Apr
2   Jun
3   Jan
4   Jan

I wanted to map the second key value (which is quarter of the year) to the dataframe to give

   Month    Quarter
0   Jan      1
1   Apr      2
2   Jun      2
3   Jan      1
4   Jan      1

Is this possible?

Upvotes: 0

Views: 39

Answers (3)

sammywemmy
sammywemmy

Reputation: 28644

Not sure if this is what you are after :

 df["Quarter"] = df["Month"].map({key: value[0] for key, value in dates.items()})



  Month  Quarter
0   Jan     1
1   Apr     2
2   Jun     2
3   Jan     1
4   Jan     1

Upvotes: 1

Arpit
Arpit

Reputation: 394

I hope this will work

quart=[]
for i in df['Month']:
    for index,key in enumerate(dates.keys()):
        if i==key:
            quart.append(dates[index][0])

df['Quarter']=quart

Upvotes: 1

Let's try
Let's try

Reputation: 1058

Try:

df["Quarter"] = df["Month"].apply(lambda x: dates[x][1])

Upvotes: 2

Related Questions