My Coding >
Programming language >
Python >
Python FAQ >
Python: How to create Pandas column based on conditions
Python: How to create Pandas column based on conditionsThis is a pretty common task, to create pandas column, based on some logical conditions on other columns. Let’s consider how to solve this task Creating test DataFrameWe will create DataFrame with 2 columns, with random letters ‘a’ and ‘b’. Read more about how to create Pandas test DataSets
Create Pandas column on conditions over other columnOur task is to create column with values ‘Yes’ is c1 contain ‘a’ and ‘No’ if c1 contains ‘b’. It is possible to have 3 basic solutions: Create column with NumPy.where()np.where() create column based on condition given.
Create column with list comprehensionIt is possible to create Pandas column as a list comprehension
Using apply with lambda functionapply() with lambda function can perform this line by line conditions for creating new column
Create Pandas column on conditions over few columnsHow to create Pandas column, based on conditions over few columns. This is a bit more complicated. For example we will create column with value ‘yes’ if column ‘c1’ equal ‘c2’ and no othervise Create column with NumPy.where()np.where() is very powerful tool for creating new columns based on conditions.
|
Last 10 artitles
9 popular artitles
|
|
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |