w3resource
Python Pandas Exercises

Pandas Datetime: Count year-country wise frequency of reporting dates of unidentified flying object (UFO)

Pandas Datetime: Exercise-10 with Solution

Write a Pandas program to count year-country wise frequency of reporting dates of unidentified flying object (UFO).

Sample Solution :

Python Code :

import pandas as pd
df = pd.read_csv(r'ufo.csv')
df['Date_time'] = df['Date_time'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
df['Year'] = df['Date_time'].apply(lambda x: "%d" % (x.year))
result = df.groupby(['Year', 'country']).size()
print("\nCountry-year wise frequency of reporting dates of UFO:")
print(result)

Sample Output:

Original Dataframe:
            Date_time                  city     ...       latitude   longitude
0 1910-06-01 15:00:00           wills point     ...      32.709167  -96.008056
1 1920-06-11 21:00:00                cicero     ...      40.123889  -86.013333
2 1929-07-05 14:00:00  buchanan  (or burns)     ...      43.642500 -118.627500
3 1931-06-01 13:00:00               abilene     ...      38.917222  -97.213611
4 1939-06-01 20:00:00              waterloo     ...      34.918056  -88.064167

[5 rows x 11 columns]

Country-year wise frequency of reporting dates of UFO:
Year  country
1910  us          1
1920  us          1
1929  us          1
1931  us          1
1939  us          2
1941  us          1
1942  us          1
1944  us          3
1945  us          4
1946  us          3
1947  us          4
1948  us          3
1949  us          4
1950  us          4
1951  ca          1
      us          3
1952  us          4
1953  us          4
1954  us          4
1955  us          4
1956  us          4
1957  us          4
1958  us          4
1959  us          4
1960  us          4
1961  us          4
1962  us          4
1963  us          4
1964  us          4
1965  us          4
                 ..
1984  us          4
1985  us          4
1986  us          4
1987  us          4
1988  us          4
1989  ca          1
      us          3
1990  us          4
1991  us          4
1992  us          8
1993  ca          1
      us         11
1994  ca          1
      us         10
1995  ca          1
      us         11
1996  us         12
1997  ca          1
      us         13
1998  us         13
1999  us         11
2000  ca          1
      us         11
2001  ca          1
      us         14
2002  ca          1
      us         13
2003  us          9
2004  ca          1
      us          6
Length: 79, dtype: int64

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to convert given datetime to timestamp.
Next: Write a Pandas program to extract unique reporting dates of unidentified flying object (UFO).

What is the difficulty level of this exercise?