為什麼DataFrame的欄位不能指派List?

79 views
Skip to first unread message

Dincht Wu

unread,
Nov 8, 2018, 11:43:19 PM11/8/18
to python.tw
import pandas as pd
d1 
= pd.DataFrame({1:[1,2,3], 2:[2,3,4], 3:[3,4,5]})
li 
= list(d1.index)
for a in range(0, len(li)):
    d1
.loc[li[a], 4] = [0, 0]

d1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-0c6a312a4fef> in <module>
      3 li = list(d1.index)
      4 for a in range(0, len(li)):
----> 5     d1.loc[li[a], 4] = [0, 0]
      6 
      7 d1

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
    187             key = com._apply_if_callable(key, self.obj)
    188         indexer = self._get_setitem_indexer(key)
--> 189         self._setitem_with_indexer(indexer, value)
    190 
    191     def _validate_key(self, key, axis):

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value)
    604 
    605                     if len(labels) != len(value):
--> 606                         raise ValueError('Must have equal len keys and value '
    607                                          'when setting with an iterable')
    608 

ValueError: Must have equal len keys and value when setting with an iterable

以上錯誤,不知道是何處有錯?
以下用新建的方式確可以放List:
import pandas as pd
d1 = pd.DataFrame({1:[1,2,3], 2:[2,3,4], 3:[3,4,5], 4:[[1, 1],[2, 2],[3, 3]]})
d1
1234
0123[1, 1]
1234[2, 2]
2345[3, 3]
Reply all
Reply to author
Forward
0 new messages