通过混合列表和数据帧列,数组长度与索引长度不匹配

时间:2017-09-29 16:12:33

标签: python pandas dataframe

我有2个数据帧和一个列表。我想将它们混合在一个pandas数据帧中。

Lista m1,Dataframe test_subdata和Dataframe predicciones:

len(m1)
438
test_subdata.shape
(438, 8)
predicciones.shape
(438, 3)

所以基本上我想这样做,一个大小为(438,3)的数据帧,其值大于:

result_frame = pd.DataFrame({'index': test_subdata['id'], 'match_1': m1, 
                             'pred1': predicciones['pred1']})

但是当我这样做时,会出现以下错误:

ValueError: array length 438 does not match index length 841

有些想法,发生了什么?

PS:当我只将一个数据帧与一个列表混合时,一切正常,即使在两个数据帧之间也是如此。

1 个答案:

答案 0 :(得分:1)

由于系列包含的索引,您将收到数组不匹配错误。因此,请先提前重置索引,或仅传递值

result_frame = pd.DataFrame({'index': test_subdata['id'].values, 'match_1': m1, 
                         'pred1': predicciones['pred1'].values})

解释

如果test_subdatapredicciones的索引不同,test_subdatapredicciones是系列的,则将从数据框构造函数创建具有非现有索引的新对象。因此,在这种情况下,数据帧大小会翻倍。 (要使现有方法有效,请确保两个数据帧都具有相同的索引。)

由于m1长度与现有索引长度不匹配,因此会出现数组长度不匹配错误。