Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

adding a pandas column with multiple conditions

# create a list of  conditions
conditions = [
    (df['likes_count'] <= 2),
    (df['likes_count'] > 2) & (df['likes_count'] <= 9),
    (df['likes_count'] > 9) & (df['likes_count'] <= 15),
    (df['likes_count'] > 15)
    ]

# create a list of the values we want to assign for each condition
choices = ['tier_4', 'tier_3', 'tier_2', 'tier_1']

# create a new column and use np.select to assign values to it using our lists as arguments
df['tier'] = np.select(conditions, choices)

# display updated DataFrame
df.head()
Comment

pandas set condition multi columns

conditions = [
   .....:     (df['col2'] == 'Z') & (df['col1'] == 'A'),
   .....:     (df['col2'] == 'Z') & (df['col1'] == 'B'),
   .....:     (df['col1'] == 'B')
   .....: ]
   .....: 

In [214]: choices = ['yellow', 'blue', 'purple']

In [215]: df['color'] = np.select(conditions, choices, default='black')

In [216]: df
Out[216]: 
  col1 col2   color
0    A    Z  yellow
1    B    Z    blue
2    B    X  purple
3    C    Y   black
Comment

pandas set condition multi columns

conditions = [
            (df['col2'] == 'Z') & (df['col1'] == 'A'),
            (df['col2'] == 'Z') & (df['col1'] == 'B'),
            (df['col1'] == 'B')
			]


choices = ['yellow', 'blue', 'purple']

df['color'] = np.select(conditions, choices, default='black')

df
# Out[216]: 
#  col1 col2   color
# 0    A    Z  yellow
# 1    B    Z    blue
# 2    B    X  purple
# 3    C    Y   black
Comment

PREVIOUS NEXT
Code Example
Python :: zlib decompress python 
Python :: sort value_counts output 
Python :: handler.setLevel(logging.DEBUG) not working python 
Python :: python prime check 
Python :: python progress bar console 
Python :: mad scipy 
Python :: pandas group by count 
Python :: how to input 2-d array in python 
Python :: comment concatener deux listes python 
Python :: python filter 
Python :: how to format integer to two digit in python 
Python :: python pip install 
Python :: python 1 to 01 
Python :: python get name of file 
Python :: python get system information 
Python :: django dumpdata 
Python :: key press python 
Python :: python dont exit script after print 
Python :: pyAudioAnalysis 
Python :: find width and height of imported video frame opencv2 
Python :: spread operator python 
Python :: json python no whitespace 
Python :: Python __gt__ magic method 
Python :: python cmath constants 
Python :: printing python dictionary values 
Python :: plt.xticks 
Python :: primary key django model 
Python :: create a role with discord.py 
Python :: Inheritance constructor with parameters python 
Python :: use datetime python to get runtime 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =