技術討論區 > Python程式設計討論區
請問老師,為什麼已建好的DF,無法指派List到欄位中?
(1/1)
dincht55:
請問老師,為什麼DataFrame不能放置list至欄位裡?
以下程式碼會出現錯誤:
import pandas as pd
d1 = pd.DataFrame({'a':[1,2,3],
'b':[2,3,4],
'c':[3,4,5]})
d1['d'] = [0, 0] # ValueError: Length of values does not match length of index
d1['d'][0] = [0, 0] # KeyError: 'd'
d1.loc[0, 'd'] = [0, 0] # ValueError: Must have equal len keys and value when setting with an iterable
但是新建的就正常了,如下:
import pandas as pd
d1 = pd.DataFrame({'a':[1,2,3],
'b':[2,3,4],
'c':[3,4,5],
'd':[[4, 4], [5, 5], [6, 6]]})
print(d1)
a b c d
0 1 2 3 [4, 4]
1 2 3 4 [5, 5]
2 3 4 5 [6, 6]
因為已建立的DF有一定的大小,要重建有難度,只能新增欄位指派List。
所以要如何在已建立的DF新增新的欄位並指派List?
導覽
[0] 文章列表
前往完整版本