Python - Pandas create column with np.where for multiple different values

I have a dataframe like this:

id year Q
1 2017 1
2 2017 2
3 2018 1
4 2018 2
5 2018 3

And would like to get this create another column called D:

id year Q Desc
1 2017 1 '2017 first Quarter'
2 2017 2 '2017 second Quarter'
3 2018 1 '2018 first Quarter' 
4 2018 2 '2018 second Quarter' 
5 2018 3 '2017 third Quarter'

Yet np.where seems to only accept 2 parameter (if true and if false). So the idea is to have a np.where sentence that can deal with multiple possibilities

3 answers

  • answered 2018-07-11 02:57 RafaelC

    Roughly, using np.select

    df['Desc'] = df.year.astype(str) + ' ' + np.select([df.Q==x for x in [1,2,3,4]], ['first', 'second', 'third', 'quarter']) + ' quarter'
    

  • answered 2018-07-11 02:57 Wen

    IIUC you just need to map your Q columns to character then using string sum

    df['Desc']=df.year.astype(str)+' '+ df.Q.map({1:'first',2:'second',3:'third',4:'fourth'})+' Quarter'
    df
    Out[26]: 
       id  year  Q                 Desc
    0   1  2017  1   2017 first Quarter
    1   2  2017  2  2017 second Quarter
    2   3  2018  1   2018 first Quarter
    3   4  2018  2  2018 second Quarter
    4   5  2018  3   2018 third Quarter
    

  • answered 2018-07-11 03:14 U9-Forward

    Use + & pandas.DataFrame.apply:

    d={1:'first',2:'second',3:'third',4:'fourth'}
    df['Desc']=(df['year'].astype(str)+' '+df['Q'].astype(str)+' Quarter').apply(lambda x: ' '.join(d[int(i)] if len(i)==1 else i for i in x.split()))
    print(df)
    

    Output:

       id  year  Q                 Desc
    0   1  2017  1   2017 first Quarter
    1   2  2017  2  2017 second Quarter
    2   3  2018  1   2018 first Quarter
    3   4  2018  2  2018 second Quarter
    4   5  2018  3   2018 third Quarter