Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Add new column based on condition on some other column in pandas.

# np.where(condition, value if condition is true, value if condition is false)

df['hasimage'] = np.where(df['photos']!= '[]', True, False)
df.head()
Comment

pandas create new column conditional on other columns

# For creating new column with multiple conditions
conditions = [
    (df['Base Column 1'] == 'A') & (df['Base Column 2'] == 'B'),
    (df['Base Column 3'] == 'C')]
choices = ['Conditional Value 1', 'Conditional Value 2']
df['New Column'] = np.select(conditions, choices, default='Conditional Value 1')
Comment

pandas create a new column based on condition of two columns

conditions = [
    df['gender'].eq('male') & df['pet1'].eq(df['pet2']),
    df['gender'].eq('female') & df['pet1'].isin(['cat', 'dog'])
]

choices = [5,5]

df['points'] = np.select(conditions, choices, default=0)

print(df)
     gender      pet1      pet2  points
0      male       dog       dog       5
1      male       cat       cat       5
2      male       dog       cat       0
3    female       cat  squirrel       5
4    female       dog       dog       5
5    female  squirrel       cat       0
6  squirrel       dog       cat       0
Comment

PREVIOUS NEXT
Code Example
Python :: sqlalchemy create engine Microsoft SQL 
Python :: jaccard distance python 
Python :: python exceptions 
Python :: boto3 read excel file from s3 into pandas 
Python :: python program to draw square 
Python :: python get latest edited file from any directory 
Python :: integer to datetime python 
Python :: returns the smallest positive integer python 
Python :: python program to solve quadratic equation 
Python :: ValueError: `logits` and `labels` must have the same shape, received ((None, 2) vs (None, 1)). 
Python :: sort by multiple keys in object python 
Python :: reverse key order dict python 
Python :: python scatter plot legend 
Python :: create exe from python script 
Python :: continual vs continuous 
Python :: hello world in python 
Python :: pandas plot move legend 
Python :: how to find the datatype of a dataframe in python 
Python :: Python Tkinter SpinBox Widget 
Python :: pandas dataframe crosstab 
Python :: python how to check if a functions been called 
Python :: how to add vertical line on subplot in matplotlib 
Python :: python tar a directory 
Python :: clamp number in python 
Python :: django content type 
Python :: else if in django template 
Python :: python how to add turtle in tkinter 
Python :: how do i convert a list to a string in python 
Python :: convert list to generator python 
Python :: pip install streamlit 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =