簡體   English   中英

將具有不同長度的列表添加為數據幀的新列

[英]Adding list with different length as a new column to a dataframe

我願意在數據框中添加或插入列表值。 數據幀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

我怎么能擺脫這個錯誤。 請幫我。

如果您將列表轉換為系列,那么它將正常工作:

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

如果您希望調用fillna可以選擇替換NaN

您可以使用任意filler標量向列表中添加項目。

來自@EdChum的數據。

filler = 0
lst = ['a', 'b']

df.loc[:, 'b'] = lst + [filler]*(len(df.index) - len(lst))

print(df)

   a  b
0  0  a
1  1  b
2  2  0

您仍然可以使用Ed中的loc數據來分配它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM