w3resource

Pandas Datetime: Get the average mean of the UFO sighting was reported

Pandas Datetime: Exercise-17 with Solution

Write a Pandas program to get the average mean of the UFO (unidentified flying object) sighting was reported.

Sample Solution:

Python Code:

import pandas as pd
#Source: https://bit.ly/32kGinQ
df = pd.read_csv(r'ufo.csv')
df['date_documented'] = df['date_documented'].astype('datetime64[ns]')
print("Original Dataframe:")
print(df.head())
# Add a new column instance, this adds a value to each instance of ufo sighting
df['instance'] = 1

# set index to time, this makes df a time series df and then you can apply pandas time series functions.
df.set_index(df['date_documented'], drop=True, inplace=True)

# create another df by resampling the original df and counting the instance column by Month ('M' is resample by month)
ufo2 = pd.DataFrame(df['instance'].resample('M').count())

# just to find month of resampled observation
ufo2['date_documented'] = pd.to_datetime(ufo2.index.values)

ufo2['month'] = ufo2['date_documented'].apply(lambda x: x.month)
print("Average mean of  the UFO (unidentified flying object) sighting was reported:")
print(ufo2.groupby(by='month').mean())

Sample Output:

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

[5 rows x 11 columns]
Average mean of  the UFO (unidentified flying object) sighting was reported:
       instance
month          
1      2.875000
2      2.500000
3      1.764706
4      2.250000
5      1.375000
6      1.187500
7      1.562500
8      2.062500
9      1.312500
10     1.687500
11     1.437500
12     1.562500

Python Code Editor:

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

Previous: Write a Pandas program to manipulate and convert date times with timezone information.
Next: Write a Pandas program to create a graphical analysis of UFO (unidentified flying object) Sightings year.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/pandas/datetime/pandas-datetime-exercise-17.php