Re: [python.tw] 為什麼DataFrame的欄位不能放List?

299 views
Skip to first unread message

Sonic Yang

unread,
Nov 11, 2018, 12:50:54 AM11/11/18
to pyth...@googlegroups.com
Hey Dincht,

第一個問題是要用at這個FUNCTION。。。因為loc會自動對齊長度。。。d1.loc[1, [2, 3]] = [30, 40]
第二個問題是用at pandas不會自動type 轉換。。。所以我把要改的那一格改成 object...才可Insert list

Best regards,
Sonic

image.png

On Fri, Nov 9, 2018 at 12:41 PM Dincht Wu <dinc...@gmail.com> wrote:
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(d2.index)
      4 for a in range(0, len(li)):
----> 5     d2.loc[li[a], 4] = [0, 0]
      6 
      7 d2

~\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]

--
這是 Google 網上論壇針對「python.tw」群組發送的訂閱通知郵件。
如要取消訂閱這個群組並停止接收來自這個群組的郵件,請傳送電子郵件到 pythontw+u...@googlegroups.com
如要在這個群組張貼留言,請傳送電子郵件到 pyth...@googlegroups.com
請前往以下網址造訪這個群組:https://groups.google.com/group/pythontw
如需更多選項,請前往:https://groups.google.com/d/optout
Message has been deleted

Dincht Wu

unread,
Nov 14, 2018, 5:33:17 AM11/14/18
to python.tw
謝謝大哥,我知道我那裡有問題了!感謝!!!
Reply all
Reply to author
Forward
0 new messages