Heisenberg
Heisenberg

Reputation: 5279

how to add column by using other column's conditions

I have a dataframe.

df=pd.DataFrame({'month':np.arange(1,8)})

So,I would like to add column by using 'month' columns

if 'month'=1,2,3   the elements = 'term1'
   'month'=4,5     the elements = 'term2' 
   'month'=6,7     the elements = 'term3'

I would like to get the result below

      month  term 
0       1    term1
1       2    term1
2       3    term1
3       4    term2
4       5    term2
5       6    term3
6       7    term3

How can I get this result? maybe we could get this result easy and simple way....

Upvotes: 0

Views: 56

Answers (2)

Zeugma
Zeugma

Reputation: 32095

I would go for a declarative way through a dict, simple to read and easy to apply. You can generate your replace condition dictionary programmatically if the replacement conditions become large or depends on other inputs:

conditions = {1:'term1', 2:'term1', 3:'term1',
              4:'term2', 5:'term2',
              6:'term3', 7:'term3'}

df['term'] = df.replace(conditions)
df

      month  term 
0       1    term1
1       2    term1
2       3    term1
3       4    term2
4       5    term2
5       6    term3
6       7    term3

Upvotes: 1

akuiper
akuiper

Reputation: 214927

Use numpy.where and Series.isin() method could be one of the options to do it:

import numpy as np
import pandas as pd
df["term"] = np.where(df.month.isin([1,2,3]), "term1", \
                      np.where(df.month.isin([4,5]), "term2", "term3"))

df
# month  term
#0    1 term1
#1    2 term1
#2    3 term1
#3    4 term2
#4    5 term2
#5    6 term3
#6    7 term3

Upvotes: 1

Related Questions