The Wayback Machine - https://web.archive.org/web/20240731145442/https://www.geeksforgeeks.org/python-pandas-dataframe-resample/
Open In App

Python | Pandas dataframe.resample()

Last Updated : 22 Oct, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas dataframe.resample() function is primarily used for time series data.
A time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time. It is a Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword.

Syntax : DataFrame.resample(rule, how=None, axis=0, fill_method=None, closed=None, label=None, convention=’start’, kind=None, loffset=None, limit=None, base=0, on=None, level=None)

Parameters :
rule : the offset string or object representing target conversion
axis : int, optional, default 0
closed : {‘right’, ‘left’}
label : {‘right’, ‘left’}
convention : For PeriodIndex only, controls whether to use the start or end of rule
loffset : Adjust the resampled time labels
base : For frequencies that evenly subdivide 1 day, the “origin” of the aggregated intervals. For example, for ‘5min’ frequency, base could range from 0 through 4. Defaults to 0.
on : For a DataFrame, column to use instead of index for resampling. Column must be datetime-like.
level : For a MultiIndex, level (name or number) to use for resampling. Level must be datetime-like.

Resampling generates a unique sampling distribution on the basis of the actual data. We can apply various frequency to resample our time series data. This is a very important technique in the field of analytics.
Most commonly used time series frequency are –
W : weekly frequency
M : month end frequency
SM : semi-month end frequency (15th and end of month)
Q : quarter end frequency

There are many other types of time series frequency available. Let’s see how to apply these time series frequency on data and resample it.

For link to CSV file Used in Code, click here

This is a stock price data of Apple for a duration of 1 year from (13-11-17) to (13-11-18)

Example #1: Resampling the data on monthly frequency




# importing pandas as pd
import pandas as pd
  
# By default the "date" column was in string format,
# we need to convert it into date-time format
  
# parse_dates =["date"], converts the "date" 
# column to date-time format. We know that 
# resampling works with time-series data only
# so convert "date" column to index
  
# index_col ="date", makes "date" column, the index of the data frame
df = pd.read_csv("apple.csv", parse_dates =["date"], index_col ="date")
  
# Printing the first 10 rows of dataframe
df[:10]





# Resampling the time series data based on months
# we apply it on stock close price
# 'M' indicates month
monthly_resampled_data = df.close.resample('M').mean()
  
# the above command will find the mean closing price
# of each month for a duration of 12 months.
monthly_resampled_data


Output :

 
Example #2: Resampling the data on weekly frequency




# importing pandas as pd
import pandas as pd
  
# We know that resampling works with time-series data
# only so convert "date" column to index
# index_col ="date", makes "date" column.
  
df = pd.read_csv("apple.csv", parse_dates =["date"], index_col ="date")
  
# Resampling the time series data based on weekly frequency
# we apply it on stock open price 'W' indicates week
weekly_resampled_data = df.open.resample('W').mean()
  
# find the mean opening price of each week 
# for each week over a period of 1 year.
weekly_resampled_data


Output :

 
Example #3: Resampling the data on Quarterly frequency




# importing pandas as pd
import pandas as pd
  
# We know that resampling works with time-series
#  data only so convert our "date" column to index
# index_col ="date", makes "date" column
df = pd.read_csv("apple.csv", parse_dates =["date"], index_col ="date")
  
# Resampling the time series data
#  based on Quarterly frequency
# 'Q' indicates quarter
  
Quarterly_resampled_data = df.open.resample('Q').mean()
  
# mean opening price of each quarter
# over a period of 1 year.
Quarterly_resampled_data


Output :



Previous Article
Next Article

Similar Reads

How to Resample Time Series Data in Python?
In time series, data consistency is of prime importance, resampling ensures that the data is distributed with a consistent frequency. Resampling can also provide a different perception of looking at the data, in other words, it can add additional insights about the data based on the resampling frequency. resample() function: It is a primarily used
5 min read
How to resample NumPy array representing an image ?
In this article, we will be Resampling a NumPy array representing an image. For this, we are using scipy package. Scipy package comes with ndimage.zoom() method which exactly does this for us by zooming into a NumPy array using spline interpolation of a given order. Default is order 3 (aka cubic). For input containing imaginary components, scipy. n
5 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
3 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
three90RightbarBannerImg