【问题标题】:How to append to the right ID's column in CSV with pandas?如何使用熊猫附加到CSV中正确的ID列?
【发布时间】:2017-04-18 20:53:41
【问题描述】:

我有一个测试文件和 100 个模型,我想在测试中进行评估。

在测试文件中有2列,第一列是ID,第二列是概率。

我希望每个模型都将其评估附加到相关 ID 旁边的新列中。

我的代码现在在彼此下构建它,如下所示:

1 0.1
2 0.12
3 0.32
1 0.21
2 0.22
3 0.17

我需要这样的表格:

1 0.1 0.21
2 0.12 0.22
3 0.32 0.17

到 csv。

我的代码如下所示:

for chunk in pd.read_csv('test_numeric_out.csv', chunksize=10000):
chunk = chunk.drop(chunk.columns[len(chunk.columns)-1], axis=1)
for model in models:
    X_test = chunk.drop(['Id'],axis=1)
    inputnames = X_test.columns.values
    X_test['p_0']=0
    X_test['p_1']=0
    X_test[ ['p_0','p_1'] ]  = model.predict_proba(X_test[inputnames])
    submission = pd.DataFrame({
        "Id":chunk['Id'],
        "Response":X_test['p_1']
        })
    if (head==0):
        submission.to_csv(proba_out_csv,
        index=False,
        header=True,
        mode='a',
        chunksize=100000)
    else:
        submission.to_csv(proba_out_csv,
        index=False,
        header=False,
        mode='a',
        chunksize=100000)
    head = 1

【问题讨论】:

  • 请修正缩进:所有行的缩进,但首先必须增加。

标签: python csv pandas random-forest


【解决方案1】:

我相信它可以做得更容易一些。

inputnames = chunk.columns.drop('Id').values
# drop works here too, so no need to create additional dataframe
# to get inputnames
for i, model in enumerate(models):
    chunk['p_1_{}'.format(i)]  = model.predict_proba(chunk[inputnames])[:, 1]
    # we are interested only in the second column
    # do not need to create different dataframe to store results
    # just create distinct column for each model
chunk.to_csv(proba_out_csv)

【讨论】:

    猜你喜欢
    • 2017-07-28
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2022-01-16
    • 2018-06-18
    • 2022-11-12
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多