我无法将numpy数组转换为pandas列。数据必须是一维/索引错误

2024-05-01 21:48:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了许多建议的解决方案,但我不能使这项工作

我有一系列的预测:

y_prob = best_model.predict_proba(data)

print(y_prob)

array([[0.32],
       [0.5 ],
       [0.32],
       ...,
       [0.46],
       [0.51],
       [0.51]], dtype=float32)

print(y_prob.shape)

(48775, 1)

我一直试图将其作为一列预测添加到原始数据框中,但我尝试的一切都不起作用

# attempt 1

data['probability'] = pd.Series(y_prob)

Exception: Data must be 1-dimensional


# attempt 2

data['probability'] = y_prob

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

# attempt 3

data['probability'] = y_prob.tolist()

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

# attempt 4

data['probability'] = [i[0] for i in y_prob]

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

# attempt etc etc etc.

我知道这可能是个愚蠢的错误。。但我就是找不到解决办法

数据维度:


print(y_prob.shape)
print(data.shape)

(48775, 1)
(48775, 121)

编辑:从评论中添加建议:

dat['probability'] = pd.Series(y_prob.reshape((y_prob.shape[0],)))

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices



data['probability'] = y_prob.ravel()

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices


data['probability'] = pd.Series(y_prob.ravel())

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Tags: orandintegersnumpynoneonlydatainteger
3条回答

我试过这个,它看起来很有效,很简单

data['probability'] = list(y_prob)

试一试

data['probability'] = pd.Series(y_prob.reshape((y_prob.shape[0],)))

这应该行得通

试试这个:

data['probability'] = pd.Series(y_prob.flatten())

相关问题 更多 >