我试图通过以下方式将我的数据集分为训练集和测试集:
for train_set, test_set in stratified.split(complete_df, complete_df["loan_condition_int"]): stratified_train = complete_df.loc[train_set] stratified_test = complete_df.loc[test_set]
我的数据框 complete_df
不包含任何 NaN
值。我通过使用 complete_df.isnull().sum().max()
确认了这一点,它返回了 0
。
但我仍然收到一个警告说:
Passing list-likes to .loc or [] with any missing label will raiseKeyError in the future, you can use .reindex() as an alternative.
这导致了后续的错误。我尝试了一些在线找到的技术,但仍然无法解决问题。
回答:
首先,您应该澄清 stratified
是什么。我假设它是 sklearn 的 StratifiedShuffleSplit
对象。
我的数据集 complete_df 不包含任何 NAN 值。
警告信息中的“缺失标签”并不是指缺失值,即 NaNs。错误信息表示 train_set
和/或 test_set
包含的值(标签)在 complete_df
的索引中不存在。这是由于 .loc
是基于行(和列)标签进行索引的,而不是基于行位置,而 train_set
和 test_set
表示的是行号。因此,如果您的 DataFrame 的索引与行的整数位置不一致(似乎就是这种情况),就会发出警告。
要按行位置选择,请使用 iloc
。这应该可以工作
for train_set, test_set in stratified.split(complete_df, complete_df["loan_condition_int"]): stratified_train = complete_df.iloc[train_set] stratified_test = complete_df.iloc[test_set]