多列条件值修正:新增df["E"]列填充指定用户时段值至当日其余时段
Got it, let's work through this problem together. You need to add a new column E to your DataFrame where for users Joseph and Emma, we take their 15:00:00 value from column D and propagate that value to all other time slots on the same day for those users. Here's a straightforward way to do this with pandas:
Step 1: Setup and Sample Data
First, let's assume your DataFrame has columns like User, Datetime, and D (adjust column names if yours differ). Here's a sample to test with:
import pandas as pd # Sample input DataFrame data = { "User": ["Joseph", "Joseph", "Emma", "Emma", "John", "John"], "Datetime": pd.to_datetime([ "2024-05-20 10:00:00", "2024-05-20 15:00:00", "2024-05-20 12:00:00", "2024-05-20 15:00:00", "2024-05-20 15:00:00", "2024-05-20 18:00:00" ]), "D": [10, 25, 15, 30, 20, 22] } df = pd.DataFrame(data)
Step 2: Extract Date and Time for Target Filtering
We first split the Datetime column into date and time components to easily target the 15:00:00 records:
# Extract date and time as separate columns (temporary, for matching) df["Date"] = df["Datetime"].dt.date df["Time"] = df["Datetime"].dt.time
Step 3: Create a Mapping of Daily 15:00 Values for Target Users
Next, we pull out the 15:00 D values for Joseph and Emma, which will be our fill values for their daily records:
# Filter rows where user is Joseph/Emma and time is 15:00:00 target_mask = (df["User"].isin(["Joseph", "Emma"])) & (df["Time"] == pd.to_datetime("15:00:00").time()) daily_fill_values = df[target_mask][["User", "Date", "D"]].rename(columns={"D": "E"})
Step 4: Merge Fill Values Back to Original DataFrame
We merge this mapping back to the original DataFrame to populate the E column for matching user-date pairs:
# Merge to get the fill values into the E column df = df.merge(daily_fill_values, on=["User", "Date"], how="left") # For non-target users (like John), set E to their original D value (adjust if you want NaN instead) df["E"] = df.apply(lambda row: row["D"] if row["User"] not in ["Joseph", "Emma"] else row["E"], axis=1) # Clean up temporary columns (optional) df = df.drop(columns=["Date", "Time"])
Final Result
Running the code above will give you this output:
User Datetime D E 0 Joseph 2024-05-20 10:00:00 10 25.0 1 Joseph 2024-05-20 15:00:00 25 25.0 2 Emma 2024-05-20 12:00:00 15 30.0 3 Emma 2024-05-20 15:00:00 30 30.0 4 John 2024-05-20 15:00:00 20 20.0 5 John 2024-05-20 18:00:00 22 22.0
Note: If your Datetime column isn't already a datetime type, make sure to convert it first with df["Datetime"] = pd.to_datetime(df["Datetime"]).
内容的提问来源于stack exchange,提问作者Tie_24

