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 :: pytest parametrize 
Python :: python matplotlib pyplot 
Python :: python find specific file in directory 
Python :: change tensor type pytorch 
Python :: sort the dictionary in python 
Python :: initialize dictionary with empty lists 
Python :: flask render_template 
Python :: python read html table 
Python :: bar plot matplotlib 
Python :: 2d array pytho 
Python :: maping value to data in pandas dataframe 
Python :: pandas map multiple columns 
Python :: finding the index of an element in a pandas df 
Python :: display youtube video in jupyter notebook 
Python :: how to get a dataframe column as a list 
Python :: renaming multiple columns in pandas 
Python :: all the positions of a letter occurrences in a string python 
Python :: Get List Into String 
Python :: create virtual env 
Python :: how to make html files open in chrome using python 
Python :: How to find xpath by contained text 
Python :: IntegrityError import in django 
Python :: django template tag multiple arguments 
Python :: ip regex python 
Python :: rename key in python dictionary 
Python :: find average of list python 
Python :: python input lowercase 
Python :: numpy drop duplicates 
Python :: how to transpose a 2d list in python 
Python :: remove all instances from list python 
ADD CONTENT
Topic
Content
Source link
Name
5+5 =