Pandas报错ValueError:仅允许传入布尔值DataFrame问题求助
ValueError: Must pass DataFrame with boolean values only When Using freq='2D' Hey there! Let's break down why this error shows up when you switch from freq='D' to freq='2D', and how to fix it quickly.
What's Causing the Issue?
When you use df.asfreq(freq='D'), the resulting index matches the daily frequency of your original data (assuming your raw data was daily). That means your is_filled boolean mask—probably created based on the original DataFrame's index—has the exact same length as df_filled, so indexing works seamlessly.
But when you switch to freq='2D', asfreq() generates an index with 2-day gaps. This new index is shorter and doesn't line up with your original is_filled mask anymore. When you try df_filled[is_filled], pandas can't map the old mask to the new DataFrame correctly, leading to that confusing "must pass boolean values only" error (the mask ends up misaligned or converted to a non-boolean type behind the scenes).
The Fix: Align Your Mask to the Processed Data
The solution is simple: recreate your is_filled mask using the processed df_filled DataFrame, not your original raw data. Here's how to adjust your code:
# First generate your filled DataFrame with 2D frequency df_filled = df.asfreq(freq='2D').fillna(method='bfill', limit=1).dropna(how='all').drop_duplicates(keep='last') # Now create is_filled based on df_filled (tweak this logic to match your actual needs) # Example: if is_filled marks rows with no missing values is_filled = df_filled.notna().any(axis=1) # Now indexing will work without errors result = df_filled[is_filled]
Customize the Mask for Your Specific Use Case
If your original is_filled had a specific purpose—like tracking which rows were successfully backfilled—adjust the mask creation to match that logic. For example, to flag rows that were filled by the bfill operation:
# Get the intermediate DataFrame before filling df_2d = df.asfreq(freq='2D') # Fill missing values df_filled = df_2d.fillna(method='bfill', limit=1).dropna(how='all').drop_duplicates(keep='last') # Create mask for rows that were originally missing but now filled is_filled = df_2d.isna().any(axis=1) & df_filled.notna().any(axis=1) # Use the aligned mask result = df_filled[is_filled]
This ensures your boolean mask always matches the index and structure of df_filled, no matter what frequency you're working with.
内容的提问来源于stack exchange,提问作者Behinoo

