如何將列中的某些單元格設置為列表列表中的列表,其中列表列表的長度與單元格的數量相同?運行我嘗試的部分時,出現以下錯誤:ValueError:使用 ndarray 設置時必須具有相等的 len 鍵和值我想要的 DataFrame,如下明確定義,desired如下所示: include array0 True [1, 2]1 False NaN2 False NaN3 True [3, 4]4 False NaN嘗試過的代碼:import pandas as pd# This is what I trieda = pd.DataFrame({'include': [True, False, False, True, False]})a.loc[a['include'], 'array'] = [[1, 2], [3, 4]]# This is what I wantdesired = pd.DataFrame({'include': [True, False, False, True, False], 'array': [[1, 2], np.nan, np.nan, [3, 4], np.nan]})
1 回答

楊__羊羊
TA貢獻1943條經驗 獲得超7個贊
不太確定你想做什么,但你可以將其轉換為 apandas.Series并對齊索引:
a.loc[a['include'], 'array'] = pd.Series([[1, 2], [3, 4]], index=[0, 3])
print(a)
include array
0 True [1, 2]
1 False NaN
2 False NaN
3 True [3, 4]
4 False NaN
要保持索引的分配通用而不是硬編碼,請使用:
a.loc[a['include'], 'array'] = pd.Series([[1, 2], [3, 4]], a[a['include']].index)
添加回答
舉報
0/150
提交
取消