我将 Pandas 与名为 df 的 DataFrame 一起使用。我正在使用它提取新功能,并将生成的两个新数据帧与 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
当我运行它时,我得到以下输出:
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)
所以我的过滤删除了原始 df 中的一行,tfidf_desc 和 tfidf_title 数据帧也有 9,999 行。我使用 axis=1 将它们与 pd.concat 连接起来,并以某种方式最终得到一个 10,000 行的 DataFrame,所有基于“Title”和“FullDescription”的数据都为 NaN特点。
知道为什么会这样吗?
谢谢!
请您参考如下方法:
过滤后,索引不会被重置。这会在连接数据帧时导致问题。在过滤 df 之后试试这个:
df= df.reset_index(drop=True)
