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

Python中DataFrame顺序错乱:如何关联RepID与正确BOW特征

解决BOW特征与RepID/ICU列关联错乱的方法

核心问题原因

你的BOW函数处理df_reps["Txt"]时,生成的dfMethod默认使用全新的连续索引(0,1,2...),但下采样后的df_reps和df_results保留原数据的非连续索引,导致三者索引不匹配,关联时出现顺序错乱。


方案一:修改BOW函数保留原索引

直接让生成的BOW特征DataFrame继承输入文本序列的索引,确保和df_reps、df_results的索引完全对齐:

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np

def BOW(df):
    CountVec = CountVectorizer() # 如需仅用双词组合,修改为ngram_range=(2,2)
    Count_data = CountVec.fit_transform(df)
    Count_data = Count_data.astype(np.uint8)
    # 关键:指定DataFrame的索引为输入df的索引
    cv_dataframe = pd.DataFrame(
        Count_data.toarray(),
        columns=CountVec.get_feature_names_out(),
        index=df.index
    )
    return cv_dataframe.astype(np.uint8)

# 生成带原索引的BOW特征
dfMethod = BOW(df_reps["Txt"])

# 直接通过索引合并RepID和ICU列
dfMethod = dfMethod.join(df_reps[["RepID"]]).join(df_results[["ICU"]])

方案二:不修改BOW函数,手动对齐索引

如果不想改动BOW函数,可手动将df_reps的索引赋值给dfMethod,再通过索引关联列:

dfMethod = BOW(df_reps["Txt"])
# 让dfMethod的索引与df_reps保持一致
dfMethod.index = df_reps.index

# 合并RepID和ICU列
dfMethod = dfMethod.merge(df_reps[["RepID"]], left_index=True, right_index=True)
dfMethod = dfMethod.merge(df_results[["ICU"]], left_index=True, right_index=True)

更严谨的前置优化:合并后再下采样

为从根源避免RepID与数据分离的问题,建议先合并两个DataFrame再执行下采样,确保所有数据始终按RepID绑定:

from imblearn.under_sampling import RandomUnderSampler

# 先合并两个DataFrame,保证RepID对应关系
df_combined = df_reps.merge(df_results, on="RepID")

# 执行下采样,以ICU列为目标平衡数据
rus = RandomUnderSampler(random_state=42)
df_combined_resampled, _ = rus.fit_resample(df_combined, df_combined["ICU"])

# 拆分回原结构
df_reps = df_combined_resampled[["RepID", "Txt"]]
df_results = df_combined_resampled[["RepID", "ICU"]]

# 再生成BOW特征,此时直接用方案一或二都能完美关联
dfMethod = BOW(df_reps["Txt"])
dfMethod = dfMethod.join(df_reps[["RepID"]]).join(df_results[["ICU"]])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:52:17