按鸟类个体及匹配时间分组计算不同时段平均体温差值
Got it, let's work through how to calculate those hourly average temperature differences for each bird across the different periods (PreI, DayI, PostI). Here's a step-by-step approach using pandas, which is perfect for this kind of tabular data manipulation:
First, we need to get the average Tb for each combination of Bird_ID, Hour, and Tb_Period. This groups the data so we're working with the hourly mean for each bird in each period—exactly what we need for the time-point comparisons.
import pandas as pd # Calculate hourly mean Tb for each Bird_ID + Hour + Tb_Period combo hourly_mean_tb = df.groupby(['Bird_ID', 'Hour', 'Tb_Period'])['Tb'].mean().reset_index()
Next, we'll pivot the data so each Tb_Period becomes a column. This puts all the hourly averages for a single bird and hour on one row, making it trivial to compute differences between periods.
# Pivot to wide format: Bird_ID + Hour as index, Tb_Period as columns wide_tb = hourly_mean_tb.pivot(index=['Bird_ID', 'Hour'], columns='Tb_Period', values='Tb').reset_index()
Your output will look something like this (example for Bird 3282 at hour 11):
| Hour | PreI | DayI | PostI |
|---|---|---|---|
| 11 | 42.1 | 42.5 | 42.3 |
Now we can calculate the specific comparisons you need—like 09:00 DayI - 09:00 PreI or 10:00 PostI - 10:00 PreI. We'll add these as new columns to our wide dataframe.
# Calculate your desired period differences (customize these as needed) wide_tb['DayI_minus_PreI'] = wide_tb['DayI'] - wide_tb['PreI'] wide_tb['PostI_minus_PreI'] = wide_tb['PostI'] - wide_tb['PreI'] # Add more if needed, e.g.: # wide_tb['PostI_minus_DayI'] = wide_tb['PostI'] - wide_tb['DayI']
If you only care about certain hours (like 09:00 and 10:00), you can filter the dataframe to focus exclusively on those time points:
# Keep only rows for hours 9 and 10 target_hours = wide_tb[wide_tb['Hour'].isin([9, 10])]
- Double-check that your
Hourcolumn is formatted as an integer (e.g., 9 for 09:00, 10 for 10:00). If it's a string, convert it first withdf['Hour'] = df['Hour'].astype(int). - If some birds are missing data for a specific period/hour, you'll get
NaNvalues in the difference columns. Handle these withfillna()(to replace with a default value) ordropna()(to remove incomplete rows) as needed. - This setup is flexible—you can easily add more period comparisons later by extending the difference calculations.
内容的提问来源于stack exchange,提问作者 S.Bird

