madelen
madelen

Reputation: 17

How to I get July month of all years in a yearly time series? (Jupyter notebook)

I need some help to get my script to plot my SPI values only for July-month. My script looks like this:

from pandas import read_csv

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import os

import cartopy

%matplotlib inline

df = pd.read_csv('SPI1_and_rr_for_200011.0.csv',header=0)

df

and it reads this:

    time                   rr          spi
0   1985-01-16 00:00:00 42.200000   0.452561
1   1985-02-14 12:00:00 52.300000   1.383562
2   1985-03-16 00:00:00 21.900000   -0.562075
3   1985-04-15 12:00:00 35.600002   0.562016
4   1985-05-16 00:00:00 22.400000   -0.699583
... ... ... ...
403 2018-08-16 00:00:00 110.400000  1.094294
404 2018-09-15 12:00:00 74.400000   0.451431
405 2018-10-16 00:00:00 44.400000   -0.071395
406 2018-11-15 12:00:00 26.100000   -1.293115
407 2018-12-16 00:00:00 51.000000   0.792487

then I plot and get this:

df.plot(y='spi',x='time')

enter image description here

Upvotes: 0

Views: 167

Answers (2)

maxcopeland
maxcopeland

Reputation: 31

Make sure df['time'] is of type datetime and use the dt accessor to filter by month.

# Convert to datetime 
df['time'] = pd.to_datetime(df['time'])

# Filter by month number (July == 7)
july_df = df[df['time'].dt.month == 7]

Upvotes: 1

Jeff Tilton
Jeff Tilton

Reputation: 1296

It would be easier to confirm if you created some sample data that I could copy and paste, but the below might get you started. Look up groupby and pd.Grouper.

df.groupby(pd.Grouper(freq='M')).getgroup(7)

You may have to convert your date time column to a pd.Timestamp, I am not sure what form it is in.

You can also see a more complete answer here.

Upvotes: 0

Related Questions