본문 바로가기

Python

ValueError: Wrong number of items passed 19, placement implies 1

1. 역시 관련 오류 검색의 출발점은 stackoverflow

https://stackoverflow.com/questions/43196907/valueerror-wrong-number-of-items-passed-meaning-and-suggestions

 

ValueError: Wrong number of items passed - Meaning and suggestions?

I am receiving the error: ValueError: Wrong number of items passed 3, placement implies 1, and I am struggling to figure out where, and how I may begin addressing the problem. I don't really under...

stackoverflow.com

그런데 읽어봐도 명쾌하게 이해가 되지는 않고 내 오류해결은 되지 않는다.

 

2. 이전 settingwithcopywarning 오류와 관계있는 CFTC 자료를 보고 있는데..

   몇 가지 column을 추가하고 싶다. 

   Netlong이 변화했는지를 나타내는 것

   ② 증가감소가 몇번 연속에 걸쳐 나타나타는지

   ③ 감소를 위한 마이너스 부호

   ④ 순매수매도변화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for item, sheet_temp in tqdm(zip(item_list, sheet_list), desc = "cftc", mininterval=0.01):
    time.sleep(0.01)
    
    wb = xw.Book(r'D:\\category\\CFTC\\new\\option\\cftctest.xlsx')
    sheet = wb.sheets[sheet_temp]
    df = COT_Org[COT_Org['Name'].isin([item])]['Netlong']- COT_Org[COT_Org['Name'].isin([item])]['Netlong'].shift(1)
    df1 = pd.DataFrame(df)
    df1.columns = ['Netlong_change']
    df2 = pd.merge(COT_Org[COT_Org['Name'].isin([item])], df1, left_index= True, right_index = True)
    df2['판단'= df2['Netlong_change'].map(증가감소판단)
    df2['Streak'= df2['판단'].groupby((df2['판단'!= df2['판단'].shift()).cumsum()).cumcount() + 1
    df2['Streak_signal'= np.where(df2['Netlong_change']< 0, df2['Streak'* (-1), df2['Streak'])
    df2["순매수매도변화"= df2.apply(lambda x: 순매수매도증감(x["Netlong"], x["Netlong_change"]), axis = 1).dropna(axis=0)
    sheet.range('a1').value = df2
cs

 

  위 4가지를 위한 column을 만들기 위해 위와 같은 코드를 만들면...

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             except KeyError:
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
 
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
 
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
 
KeyError: '순매수매도변화'
 
During handling of the above exception, another exception occurred:
 
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1070         try:
-> 1071             loc = self.items.get_loc(item)
   1072         except KeyError:
 
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
 
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
 
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
 
KeyError: '순매수매도변화'
 
During handling of the above exception, another exception occurred:
 
ValueError                                Traceback (most recent call last)
<ipython-input-137-5081f4b6ddf0> in <module>
     11     df2['Streak'= df2['판단'].groupby((df2['판단'!= df2['판단'].shift()).cumsum()).cumcount() + 1
     12     df2['Streak_signal'= np.where(df2['Netlong_change']< 0, df2['Streak'* (-1), df2['Streak'])
---> 13     df2["순매수매도변화"= df2.apply(lambda x: 순매수매도증감(x["Netlong"], x["Netlong_change"]), axis = 1).dropna(axis=0)
     14     sheet.range('a1').value = df2
 
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   2936         else:
   2937             # set column
-> 2938             self._set_item(key, value)
   2939 
   2940     def _setitem_slice(self, key, value):
 
~\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   2999         self._ensure_valid_index(value)
   3000         value = self._sanitize_column(key, value)
-> 3001         NDFrame._set_item(self, key, value)
   3002 
   3003         # check if we are modifying a copy
 
~\Anaconda3\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
   3622 
   3623     def _set_item(self, key, value) -> None:
-> 3624         self._data.set(key, value)
   3625         self._clear_item_cache()
   3626 
 
~\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1072         except KeyError:
   1073             # This item wasn't present, just insert at end
-> 1074             self.insert(len(self.items), item, value)
   1075             return
   1076 
 
~\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in insert(self, loc, item, value, allow_duplicates)
   1179         new_axis = self.items.insert(loc, item)
   1180 
-> 1181         block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
   1182 
   1183         for blkno, count in _fast_count_smallints(self._blknos[loc:]):
 
~\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in make_block(values, placement, klass, ndim, dtype)
   3045         values = DatetimeArray._simple_new(values, dtype=dtype)
   3046 
-> 3047     return klass(values, ndim=ndim, placement=placement)
   3048 
   3049 
 
~\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
   2593             values = np.array(values, dtype=object)
   2594 
-> 2595         super().__init__(values, ndim=ndim, placement=placement)
   2596 
   2597     @property
 
~\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
    123         if self._validate_ndim and self.ndim and len(self.mgr_locs) != len(self.values):
    124             raise ValueError(
--> 125                 f"Wrong number of items passed {len(self.values)}, "
    126                 f"placement implies {len(self.mgr_locs)}"
    127             )
 
ValueError: Wrong number of items passed 19, placement implies 1
 
cs

 

  위와 같은 에러를 뱉어낸다. 

  길기도 하다.

  KeyError: '순매수매도변화'에서 오류가 출발했기 때문에 커스텀 함수 적용시

  무언가 문제가 발생한 것을 추론할 수 있다.

 

1
2
3
4
5
6
7
sheet_list = ['SRW''HRW''HRS','Corn''dollar']
 
item_list = ['WHEAT-SRW - CHICAGO BOARD OF TRADE',
             'WHEAT-HRW - CHICAGO BOARD OF TRADE',
             'WHEAT-HRSpring - MINNEAPOLIS GRAIN EXCHANGE',
             'CORN - CHICAGO BOARD OF TRADE',
             'U.S. DOLLAR INDEX - ICE FUTURES U.S.' ]
cs

 

  몇 가지를 찾아보는 중에 item_list 중 문제는 리스트 중에 'U.S. DOLLAR INDEX - ICE FUTURES U.S.'

  이 놈이 문제였다. 읽어들인 CFTC 자료 중에 위 품목이 없었다. 

  즉 '순매수매도변화' 생성을 위한 column을 만들기 위해

  Date, Prod_Merc_Long, Prod_Merc_Short, Swap_Long, Swap_Short, M_Money_Long, M_Money_Short,   

  Other_Rept_Long, Other_Rept_Short, Name, OI, Year, Month, M_Money ratio, Netlong, Netlong_change,

  판단, Streak, Streak_signal 이라는 19개의 column 데이터가 없어서 

  "ValueError: Wrong number of items passed 19, placement implies 1" 오류를 뱉어내는 것이다. 

  지금까지 수 많은 오류를 경험했지만 결국 데이터 문제였던 적이 대다수....

 

3. 왜 이런 실수를?

   CFTC 자료가  과거 변화를 거치면서 과거 형식의 자료와 세부적인 내용의 자료가 상이해서 나타나는 문제이다. 

   특히 환 관련한 자료는 M_Money_Positions_Long_ALL, M_Money_Positions_Short_ALL과 같은

   세부적인 구분자료가 발표가 안되네?

   이제와서 알다니?