python - 如何使用for循环 append 从python中的函数生成的数据框

标签 python pandas append scikit-learn

我的问题是我生成了一个函数来存储每个分类器中每个逐步模型的 10 折交叉验证分数。例如,对于朴素贝叶斯,我有两个模型,一个只使用一个变量,而其他的使用两个。类似于决策树模型。函数类似于

def crossV(clf):
    cvOutcome=pd.DataFrame()
    index=pd.DataFrame()
    classifier=pd.DataFrame()
    for i in range(4)[2:]:
        tt=array(tuple(x[1:i] for x in modelDataFullnew))
        qq=array(tuple(x[0] for x in modelDataFullnew))
        scores=cross_validation.cross_val_score(clf, tt, qq, cv=10)*100
        index_i=list(np.repeat(i-1,10))
        classifier_i=list(np.repeat(str(clf)[:-2],10))
        scores=list(scores)
        cvOutcome=cvOutcome.append(scores)
        index=index.append(index_i)
        classifier=classifier.append(classifier_i)
    merge=pd.concat([index,cvOutcome,classifier],axis=1)
    merge.columns=['model','rate','classifier']
    return(merge)

from sklearn.naive_bayes import GaussianNB as gnb
clf_nb=gnb()
from sklearn import tree
clf_dt=tree.DecisionTreeClassifier()

如果我执行 crossV(clf_nb) 它会给我结果

    model   rate    classifier
   1     92.558679   GaussianNB
   1     92.558381   GaussianNB
   1     92.558381   GaussianNB
   1     92.558381   GaussianNB
   1     92.558381   GaussianNB

我的问题是如何将此函数应用于多个分类器并将它们的结果 append 为长数据框,例如

    model   rate    classifier
   1     92.558679   GaussianNB
   1     92.558381   GaussianNB
   1     92.558381   GaussianNB
   1     92.558381   GaussianNB
   1     92.558381   GaussianNB
   1     93.25       DecisionTree
   1     93.25       DecisionTree

我试过这段代码,但它不起作用:

hhh=[clf_nb,clf_dt]

g=pd.DataFrame()
while i in hhh:
    g=g.append(crossV(i))

我也试过数组中的 map 函数,比如

map(crossV,(clf_nb,clf_dt)) 

它有效,但只是给我一个更大的列表,我不知道如何将它转换为数据框。

最佳答案

clf = [clf_nb, clf_dt]

cross_clf = [ crossV(x) for x in clf ]

df = pd.concat( cross_clf )

编辑:

您在评论中的问题示例:

我需要 i = clf_nbi = clf_nb 来启动 while

hhh = [clf_nb, clf_dt]

g = pd.DataFrame()

i = clf_nb

while i in hhh: # if `clf_nb` is still on the list `hhh` then ...
    g.append( crossV(i) ) # append `clf_nb` to the `g`

但是 i 总是等于 clf_nbclf_nb 总是在列表 hhh 上所以你有无限循环,总是将 clf_nb 添加到 g

关于python - 如何使用for循环 append 从python中的函数生成的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623323/

相关文章:

python - ValueError : Layer weight shape (43, 100) 与提供的权重形状不兼容 (412457, 400)

python - 将字典列表转换为数据框

python - 如何对 pandas 数据帧的多列上的逻辑运算符进行向量化?

python - 将一些列 append 到列表矩阵的列表中

javascript - 将变量值放入 jQuery 的追加中

python - 类中的嵌套列表

python - 如何根据 PySpark 数据框另一列中的值修改一列? F.when 边缘情况

python - Pyspark 在查找前一行时按组迭代数据帧

python - 如何获得 Python Selenium 中的最后一个类

python - Dataframe pandas 如何将列表作为列传递