如何替换MultiIndex中的特定值?多索引DataFrame替换操作问询
Got it, let's work through this problem step by step. First, a quick correction to your initial condition: pd.to_datetime(data_pivot.index.get_level_values(0)).dayofweek==6 checks if the current row's date is Sunday (since pandas uses dayofweek=0 for Monday, 6 for Sunday). But your requirement targets rows where the previous row's date is Saturday (which is dayofweek=5). We'll fix that logic first.
Another critical note: pandas MultiIndex objects are immutable—you can't edit their values directly. So we'll need to convert the index to regular columns, make our changes, then rebuild the MultiIndex. Here's the full workflow:
Convert MultiIndex to regular columns
This lets us easily modify the cluster values without dealing with the immutable index:# Reset index to turn MultiIndex levels into columns df = data_pivot.reset_index() # Optional: Rename columns to match your level names (adjust as needed) df.columns = ['date', 'cluster', *data_pivot.columns.tolist()]Create the correct mask for rows to modify
We need two conditions combined:- The previous row's date is a Saturday (
dayofweek=5) - The current row's cluster value is 1
# Ensure the date column is in datetime format df['date'] = pd.to_datetime(df['date']) # Get the day of week for the date in the row above prev_dayofweek = df['date'].shift(1).dt.dayofweek # Combine both conditions into a boolean mask mask = (prev_dayofweek == 5) & (df['cluster'] == 1)- The previous row's date is a Saturday (
Update the cluster values
Use the mask to set matching cluster entries to 4:df.loc[mask, 'cluster'] = 4Recreate the MultiIndex
Convert the modified columns back to the original MultiIndex structure:# Set the index back to the two-level structure data_pivot_modified = df.set_index(['date', 'cluster'])
If you want to adapt your original boolean array approach (just fixing the date condition), here's how to integrate it:
# Extract the date level from the MultiIndex dates = pd.to_datetime(data_pivot.index.get_level_values(0)) # Check if the previous row's date was Saturday prev_is_saturday = dates.shift(1).dt.dayofweek == 5 # Check if current row's cluster is 1 cluster_is_1 = data_pivot.index.get_level_values(1) == 1 # Combine into the final mask mask = prev_is_saturday & cluster_is_1 # Then follow steps 1-4 above to reset index, apply changes, and rebuild the MultiIndex
The core idea here is that MultiIndexes can't be edited in-place—breaking them down to columns, making your updates, then rebuilding the index is the reliable way to make these changes.
内容的提问来源于stack exchange,提问作者knieger

