Write a program in Python to count the total number of leap years in a given DataFrame

PythonPandasServer Side ProgrammingProgramming

Input

Assume, DataFrame is,

DataFrame is
  year days
0 2002 365
1 2004 366
2 2012 366
3 2018 365
4 2020 366

Output

``python Count the number of leap years are:- 3 ```

Solution

To solve this, we will follow the below approaches.

  • Define a DataFrame

  • Set the condition year%4==0 and days==366 to verify the DataFrame value. It is defined below,

df[(df['year']%4==0) & (df['days']==366)]
  • Finally, print the length of DataFrame.

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
data = { 'year':[2002,2004,2012,2018,2020], 'days': [365,366,366,365,366]}
df = pd.DataFrame(data)
df1 = df[(df['year']%4==0) & (df['days']==366)]
print("Count is", len(df1))

Output

Count is 3
raja
Published on 11-Feb-2021 09:48:55
Advertisements