How to use multiple columns In Python
Condition 1: Likes are less than 20 AND view more than 30.
For satisfying two or more conditions, wrap each condition in brackets( ) and then use single & sign to separate them. Here we have only two conditions, so we need only one &.
Python3
import pandas as pd # Data my_data = { "views" : [ 12 , 13 , 100 , 80 , 91 ], "likes" : [ 3 , 8 , 23 , 17 , 56 ]} my_df = pd.DataFrame(my_data) # DataFrame # Printing the DataFrame print (my_df.to_string()) # Calculating the number of views greater than 30 # as well as likes less than 20 sum = sum ((my_df.likes < 20 ) & (my_df.views > 30 )) print ( "Likes less than 20 and Views more than 30: " , sum ) |
Output
Condition 2: Using OR condition
We will use a single | sign to separate the conditions. | is used as either the first condition OR second OR third and so on.
Python3
import pandas as pd # Data my_data = { "views" : [ 12 , 13 , 100 , 80 , 91 ], "likes" : [ 3 , 8 , 23 , 17 , 56 ]} my_df = pd.DataFrame(my_data) # DataFrame # Printing the DataFrame print (my_df.to_string()) # Calculating the number of views greater than 30 # or likes less than 20 sum = sum ((my_df.likes < 20 ) | (my_df.views > 30 )) print ( "Likes less than 20 or Views more than 30: " , sum ) |
Output
How to Perform a COUNTIF Function in Python?
In this article, we will discuss how to perform a COUNTIF function in Python.
Contact Us