Below is an example Python snippet using pandas that gives you the option to resample your data on a daily, bi-daily (every 2 days), or tri-daily (every 3 days) basis. Just set the frequency_option variable to 'daily', 'bi-daily', or 'tri-daily' as needed.
# Define the input CSV file path
file_path = 'your_file.csv' # Replace with your actual CSV file path
# Read the CSV file and parse the datetime column
df = pd.read_csv(file_path, parse_dates=['datetime']) # Adjust 'datetime' to your timestamp column name
# Set the datetime column as the index to facilitate resampling
df.set_index('datetime', inplace=True)
# Choose the frequency option: 'daily', 'bi-daily', or 'tri-daily'
frequency_option = 'daily' # Change this value as needed
# Map the frequency option to a pandas resample rule
if frequency_option == 'daily':
elif frequency_option == 'bi-daily':
elif frequency_option == 'tri-daily':
raise ValueError("Invalid frequency option. Choose 'daily', 'bi-daily', or 'tri-daily'.")
# Resample to the chosen frequency and compute the mean for each period
df_resampled = df.resample(freq_rule).mean()
# If you want the datetime as a column again, reset the index
df_resampled.reset_index(inplace=True)
# Build the output filename by appending an indicator for the frequency option before the file extension
base, ext = os.path.splitext(file_path)
output_path = f"{base}_{frequency_option.upper()}{ext}"
# Save the resampled data to a new CSV file
df_resampled.to_csv(output_path, index=False)
print(f"Data resampled to {frequency_option} averages saved to {output_path}")
- Reading and Parsing: The CSV is read with
pd.read_csv and the datetime column is parsed.
- Setting the Index: The datetime column is set as the DataFrame index so that pandas can easily resample the data.
- Choosing Frequency: Based on the value of
frequency_option, a corresponding pandas resample rule is assigned:
- Daily:
'D'
- Bi-daily (every 2 days):
'2D'
- Tri-daily (every 3 days):
'3D'
- Resampling: The
.resample(freq_rule).mean() function computes the average of all numeric columns for each period.
- Saving the File: The output file is saved with the original filename appended with the frequency indicator (e.g.,
_DAILY) in the same directory.
This snippet keeps the original structure of your data (i.e. same columns) while aggregating the data into the desired time intervals.