1

I have a dataframe like this

Anno | Mese
___________
2018 | Gennaio
2019 | Febbraio
2020 | Aprile

If the values of Mese are: Gennaio, Febbraio, Marzo --> i want Anno to be year_Q1 If the values of Mese are: Aprile, Maggio, Giugno, --> i want Anno to be year_Q2 If the values of Mese are: Luglio, Agosto, Settembre, --> i want Anno to be year_Q3 If the values of Mese are: Ottobre, Novembre, Dicembre --> i want Anno to be year_Q4

My expected output is:

Anno | Mese
___________
2018_Q1 | Gennaio
2019_Q1 | Febbraio
2020_Q2 | Aprile

How can I do it in an efficient way in Pandas?

1 Answer 1

1

Use Series.map by dictionary with chnged dictionary and add to anno column:

d = {'Q1': ['Gennaio', 'Febbraio', 'Marzo'],
     'Q2': ['Aprile', 'Maggio', 'Giugno'],
     'Q3': ['Luglio', 'Agosto', 'Settembre'],
     'Q4': ['Ottobre', 'Novembre', 'Dicembre']}

#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}

df['Anno'] = df['Anno'].astype(str) + '_' + df['Mese'].map(d1)
print (df)
      Anno      Mese
0  2018_Q1   Gennaio
1  2019_Q1  Febbraio
2  2020_Q2    Aprile
Sign up to request clarification or add additional context in comments.

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.