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

将每日快照统计改为月度时触发cannot reindex from a duplicate axis错误

问题原因

你犯了一个细节错误:原代码中的dat_col是列名字符串(比如类似"date"的字符串),但你把dat_col1赋值成了df['dat_col1']——也就是DataFrame的列数据(Series对象)。当用Series作为groupby的分组键时,后续的unstack操作会因索引重复或分组逻辑混乱,触发"cannot reindex from a duplicate axis"错误。

解决办法

1. 修正列名引用

把dat_col1 = df['dat_col1']改成dat_col1 = 'dat_col1',用列名字符串代替Series对象,和原代码的dat_col用法保持一致。

2. (可选)清理无效日期

因为你用了errors='coerce',日期转换后可能产生空值,建议提前过滤掉,避免干扰统计:

df = df.dropna(subset=['dat_col1'])

3. 替换后的完整代码

# 日期转换部分
df['dat_col1'] = pd.to_datetime(df[dat_col], errors='coerce').dt.to_period('M')
df = df.dropna(subset=['dat_col1'])  # 清理无效值
dat_col1 = 'dat_col1'  # 用列名字符串

# 月度快照统计部分
if num_domains <= max_domains_for_plotting:
    df_domains_snapshot = df.groupby([dat_col1, col]).size().reset_index(name='count')
    df_domains_snapshot['pct'] = df_domains_snapshot['count'] / df_domains_snapshot.groupby([dat_col1])['count'].transform('sum')
    df_domains_all = df.groupby([col]).size().reset_index(name='count')
    df_domains_all['pct'] = df_domains_all['count'] / df_domains_all['count'].sum()
    stackedbar_abs = df.groupby([dat_col1, col]).size().unstack().plot(kind='bar', stacked=True)
    stackedbar_pct = df.groupby(dat_col1)[col].value_counts(normalize=True).unstack(col).plot.bar(stacked=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:20:25