将不同长度的列表作为新列添加到数据框

新手上路,请多包涵

我愿意在数据框中添加或插入列表值。数据帧 len 是 49 ,而列表 id 的长度 47 。实现代码时出现以下错误。

 print("Lenght of dataframe: ",datasetTest.open.count())
print("Lenght of array: ",len(test_pred_list))
datasetTest['predict_close'] = test_pred_list

错误是:

 ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-105-68114a4e9a82> in <module>()
      5 # datasetTest = datasetTest.dropna()
      6 # print(datasetTest.count())
----> 7 datasetTest['predict_close'] = test_pred_list
      8 # test_shifted['color_predicted'] = test_shifted.apply(determinePredictedcolor, axis=1)
      9 # test_shifted['color_original'] =

c:\python35\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   2517         else:
   2518             # set column
-> 2519             self._set_item(key, value)
   2520
   2521     def _setitem_slice(self, key, value):

c:\python35\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   2583
   2584         self._ensure_valid_index(value)
-> 2585         value = self._sanitize_column(key, value)
   2586         NDFrame._set_item(self, key, value)
   2587

c:\python35\lib\site-packages\pandas\core\frame.py in _sanitize_column(self, key, value, broadcast)
   2758
   2759             # turn me into an ndarray
-> 2760             value = _sanitize_index(value, self.index, copy=False)
   2761             if not isinstance(value, (np.ndarray, Index)):
   2762                 if isinstance(value, list) and len(value) > 0:

c:\python35\lib\site-packages\pandas\core\series.py in _sanitize_index(data, index, copy)
   3119
   3120     if len(data) != len(index):
-> 3121         raise ValueError('Length of values does not match length of ' 'index')
   3122
   3123     if isinstance(data, PeriodIndex):

ValueError: Length of values does not match length of index

我怎样才能摆脱这个错误。请帮我。

原文由 Jaffer Wilson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 696
2 个回答

如果您将列表转换为系列,那么它将正常工作:

 datasetTest.loc[:,'predict_close'] = pd.Series(test_pred_list)

例子:

 In[121]:
df = pd.DataFrame({'a':np.arange(3)})
df

Out[121]:
   a
0  0
1  1
2  2

In[122]:
df.loc[:,'b'] = pd.Series(['a','b'])
df

Out[122]:
   a    b
0  0    a
1  1    b
2  2  NaN

文档将此称为 带有放大的设置, 它讨论添加或扩展,但它也适用于长度小于预先存在的索引的情况。

要处理索引不从 0 开始或者实际上不是 int 的位置:

 In[126]:
df = pd.DataFrame({'a':np.arange(3)}, index=np.arange(3,6))
df

Out[126]:
   a
3  0
4  1
5  2

In[127]:
s = pd.Series(['a','b'])
s.index = df.index[:len(s)]
s

Out[127]:
3    a
4    b
dtype: object

In[128]:
df.loc[:,'b'] = s
df

Out[128]:
   a    b
3  0    a
4  1    b
5  2  NaN

您可以选择替换 NaN 如果您希望调用 fillna

原文由 EdChum 发布,翻译遵循 CC BY-SA 4.0 许可协议

您仍然可以使用 loc 来自 Ed 的数据来分配它

l = ['a','b']
df.loc[range(len(l)),'b'] = l
df
Out[546]:
   a    b
0  0    a
1  1    b
2  2  NaN

原文由 BENY 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题