You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas报错ValueError:仅允许传入布尔值DataFrame问题求助

Fixing the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:58:14