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

使用assert_frame_equal断言DataFrame时触发AssertionError:索引频率不匹配问题求助

Fixing AssertionError: Mismatched DateTimeIndex Frequency in Pandas

That error you're hitting is exactly what you suspected—your expected and actual DataFrames have mismatched freq attributes on their DateTimeIndexes. Let’s break down why your current setup might not be working, and walk through straightforward fixes.

Why Your Current Code Isn’t Sticking

When you manually set df_expected.index.freq='10s', pandas doesn’t always recognize the raw string as a valid frequency object. The freq attribute expects a proper DateOffset instance (like pd.Timedelta('10s')), and direct string assignment can fail to register correctly behind the scenes.

Solutions

1. Create the DateTimeIndex with Frequency Upfront (Most Reliable)

Instead of converting a string column and setting the index later, use pd.date_range to build your index directly with the correct frequency. This guarantees the freq attribute is properly configured from the start:

import pandas as pd

# Build index with explicit 10-second frequency
dates = pd.date_range('2019-02-07 21:11:00', periods=3, freq='10S')
df_expected = pd.DataFrame({
    'letters': ['a', 'b', 'c'],
    'counts': [1, 2, 3],
}, index=dates)

2. Properly Assign Frequency to an Existing Index

If you need to keep your original workflow of converting a string column, assign a valid DateOffset object instead of a raw string:

df_expected = pd.DataFrame({
    'date': ['2019-02-07 21:11:00','2019-02-07 21:11:10','2019-02-07 21:11:20'],
    'letters': ['a','b','c'],
    'counts': [1,2,3],
})
df_expected['date'] = pd.to_datetime(df_expected['date'])
df_expected.set_index('date', inplace=True)

# Use a DateOffset instance for reliable frequency assignment
df_expected.index.freq = pd.DateOffset(seconds=10)
# Alternatively, let pandas infer the frequency automatically
# df_expected.index.freq = pd.infer_freq(df_expected.index)

3. Skip Frequency Check in the Assertion

If you don’t need to validate the index frequency (only the index values and data content), you can disable the frequency check in assert_frame_equal:

from pandas.testing import assert_frame_equal

# Bypass frequency validation entirely
assert_frame_equal(expected, actual, check_freq=False)

Verify the Fix

After applying any of these changes, confirm the frequency is set correctly by running:

print(df_expected.index.freq)

You should see <10 * Seconds> matching your actual DataFrame’s index frequency.

内容的提问来源于stack exchange,提问作者jurassicparkcoffee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:57:47