【问题标题】:How to match array length and index length如何匹配数组长度和索引长度
【发布时间】:2019-03-01 14:44:10
【问题描述】:

我想将两个数值列组合成一个数据集,并将其保存为 .csv 文件。

它实际上是来自 Kaggle 的泰坦尼克数据集。

首先,我将特征工程的训练和测试数据集合并为:

split = len(train)
data =  pd.concat(objs=[train, test], axis=0).reset_index(drop=True)

然后我将它们拆分为模型训练:

#Split data
train = data[:split]
test = data[split:]

#Get variables for a model
x = train.drop(["Survived", "PassengerId"], axis=1)
y = train["Survived"]

#Do train data splitting
X_train, X_test, y_train, y_test = train_test_split(x,y,test_size=0.22, random_state=101)

现在,我想生成一个我尝试过的提交文件:

Id = test['PassengerId']
pred = vc.predict(X_test)

output = pd.DataFrame({
   'PassengerId' : Id, 
   'Survived': pred 
})

output.to_csv('~/Documents/Titanic/submission.csv', index=False)

...whih 返回标题中的错误:

数组长度 195 与索引长度 418 不匹配

第三行

" '幸存者': pred "

我尝试使用 pd.concat().reset_index() 代替 DataFrame,但产生了 TypeError“无法连接类型为“”的对象。

也许我现在看得太久了,但无法真正看到问题所在。 提前谢谢其他人。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    其实我已经解决了这个问题,所以我会回答我的问题。

    解决办法是:

    Id = test['PassengerId']
    pred = vc.predict(X_test)
    
    output = pd.concat([pd.DataFrame(Id), pd.DataFrame(pred)], axis=1)
    
    output.to_csv('~/Documents/Titanic/submission.csv', index=False, header=True)
    

    干杯。

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多