Pandas:Concat 意外添加了一行

bcl*_*man 5 python dataframe pandas

我正在将 Pandas 与名为 的 DataFrame 一起使用df。我正在用它提取新功能,并将生成的两个新数据帧与pd.concat. 这是我的功能:

def get_processed_df(df, rare_cols, threshold=10):
    print("df at start", df.shape)

    df = df[pd.notnull(df["FullDescription"]) &  
            pd.notnull(df["Title"]) & 
            pd.notnull(df["SalaryNormalized"])]
    print("df after filtering nulls", df.shape)

    tfidf_desc = get_tfidf_df(df, 
                              "FullDescription", 
                              max_features=100, 
                              prefix="DESC", 
                              tokenize=tokenize)
    print("tfidf_desc shape: ", tfidf_desc.shape)

    tfidf_title = get_tfidf_df(df, 
                               "Title", 
                               max_features=100, 
                               prefix="TITLE", 
                               tokenize=tokenize)
    print("tfidf_title shape: ", tfidf_title.shape)

    df.drop("FullDescription", inplace=True, axis=1)
    df.drop("Title", inplace=True, axis=1)

    final_df = pd.concat([df, tfidf_desc, tfidf_title], axis=1)
    print("final df shape: ", final_df.shape)

    return final_df
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到以下输出:

df at start (10000, 12)
df after filtering nulls (9999, 12)
tfidf_desc shape:  (9999, 100)
tfidf_title shape:  (9999, 100)
final df shape:  (10000, 210)
Run Code Online (Sandbox Code Playgroud)

所以我的过滤删除了原始数据中的一行,并且df数据帧也有 9,999 行。我用 using将它们连接起来,最终得到了 10,000 行的 DataFrame,所有基于“标题”和“完整描述”的功能都带有 NaN。tfidf_desctfidf_titlepd.concataxis=1

知道为什么会发生这种情况吗?

谢谢!

小智 3

过滤后,索引不会重置。这会在连接数据帧时导致问题。过滤后试试这个df

df= df.reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)