Pandas + Scikit学习:分层k-fold的问题

时间:2015-07-06 08:04:16

标签: pandas scikit-learn

当与Dataframe一起使用时,来自Scikit的StratifiedKFold会返回一个从0到n的索引列表,而不是DF索引中的值列表。有没有办法改变它?

前:

df = pd.DataFrame()
df["test"] = (0, 1, 2, 3, 4, 5, 6)
df.index   = ('a', 'b', 'c', 'd', 'e', 'f', 'g')
for i, (train, test) in enumerate(StratifiedKFold(df.index)):
    print i, (train, test)

给出:

0 (array([], dtype=64), array([0,1,2,3,4,5,6])
1 (array([0,1,2,3,4,5,6]), array([], dtype=64))
2 (array([0,1,2,3,4,5,6]), array([], dtype=64))

我会从df的索引中返回,而不是df的长度范围......

1 个答案:

答案 0 :(得分:3)

您获得的数字只是df.index选择的StratifiedKFold的索引。

要将其更改回DataFrame的索引,只需

for i, (train, test) in enumerate(StratifiedKFold(df.index)):
    print i, (df.index[train], df.index[test])

给出了

0 (Index([], dtype='object'), Index([u'a', u'b', u'c', u'd', u'e', u'f', u'g'], dtype='object'))
1 (Index([u'a', u'b', u'c', u'd', u'e', u'f', u'g'], dtype='object'), Index([], dtype='object'))
2 (Index([u'a', u'b', u'c', u'd', u'e', u'f', u'g'], dtype='object'), Index([], dtype='object'))