【发布时间】:2019-09-22 20:36:07
【问题描述】:
在我尝试将标题加载到数据框之前,我的代码字很好。这似乎是 np.concatenate 的问题。
我尝试过转置数组以查看它是否在错误的方向上。
print("\n")
print("Prediction")
Y = vectorizer.transform(df['plot_keywords'].astype('U'))
prediction = model.predict(Y)
df_tmp = np.concatenate([df, pd.DataFrame(np.transpose(prediction.astype(np.int32)), columns=['cluster_plot_keywords'])], axis=1)
#!!!this is where the error is, caused by the np.concatenate!!!
df = pd.DataFrame(df_tmp, columns=[np.concatenate([df.columns.values,'cluster_plot_keywords'])])
预期的结果是我可以编写 df 并打印数据框。
我在为数据框创建标头时收到以下错误:
ValueError Traceback (most recent call last)
<ipython-input-12-42a155bf519f> in <module>
7
8 #!!!this is where the error is, caused by the np.concatenate!!!
----> 9 df = pd.DataFrame(df_tmp, columns=[np.concatenate([df.columns.values,'cluster_plot_keywords'])])
ValueError: all the input arrays must have same number of dimensions
如果我打印 df_tmp,它会正确输出数组,但不会作为数据框输出,这就是我尝试在列中加载的原因:
array([['Color', 'James Cameron', 723.0, ..., 1.78, 33000, 0],
['Color', 'Gore Verbinski', 302.0, ..., 2.35, 0, 0],
['Color', 'Sam Mendes', 602.0, ..., 2.35, 85000, 0],
...,
['Color', 'Benjamin Roberds', 13.0, ..., nan, 16, 2],
['Color', 'Daniel Hsia', 14.0, ..., 2.35, 660, 2],
['Color', 'Jon Gunn', 43.0, ..., 1.85, 456, 1]], dtype=object)
【问题讨论】:
-
您似乎正在尝试将
df.columns.values与字符串'cluster_plot_keywords'连接起来。也许你的意思是predictions['cluster_plot_keywords']? -
np.concatenate是一个numpy函数。它将输入转换为ndarray,并返回ndarray。这就是您使用df_tmp看到的内容。您不应该使用一些pandas函数来组合或合并两个数据帧吗?在第二次使用中,您不希望columns成为字符串的list吗?同样,为什么要使用np.concatenate?df.columns.values是什么?列表?大批?字符串? -
列名的列表连接:
df.columns.tolist()+df_temp.columns.tolist()