如何在Pandas DataFrame中按日期计算uv_index最大值并新增uv_max列
Add a daily maximum UV index column to a time-series Pandas DataFrame
Here's a straightforward, efficient way to create the uv_max column you need, using Pandas' built-in grouping and transformation tools:
Step 1: Ensure your datetime column is properly formatted
First, make sure your date time column is parsed as a datetime type (this is critical for grouping by date later). If it's currently stored as a string, convert it:
import pandas as pd # Convert the datetime column if it's not already a datetime type df['date time'] = pd.to_datetime(df['date time'])
Step 2: Calculate and assign the daily maximum values
Use groupby combined with transform to compute the daily UV index maximum and broadcast it to every row in your DataFrame:
# Group rows by their calendar date, compute max uv_index, and assign to uv_max df['uv_max'] = df.groupby(df['date time'].dt.date)['uv_index'].transform('max')
What this does
df['date time'].dt.dateextracts just the calendar date (e.g.,2016-01-01) from the full timestamp, letting us group all hourly entries for the same day together.transform('max')calculates the highestuv_indexvalue for each daily group, then copies that maximum value to every row in the original group. This ensures every entry gets the correct daily maximum in the newuv_maxcolumn.
After running this code, print(df.head(24)) will produce exactly the output you expected—all rows for 2016-01-01 will have uv_max set to 2.0, matching the peak UV index from that day.
内容的提问来源于stack exchange,提问作者CG7
相关产品推荐
相关产品推荐

