我正在嘗試從字典創建一個非常簡單的 Pandas DataFrame。字典有 3 個專案,DataFrame 也有。他們是:
- 帶有“形狀”的串列 (3,)
- 形狀為 (3, 3) 的串列/np.array(在不同的嘗試中)
- 常數 100(整列的值相同)
- 這是成功并顯示首選df的代碼
???
# from a dicitionary
>>>dict1 = {"x": [1, 2, 3],
... "y": list(
... [
... [2, 4, 6],
... [3, 6, 9],
... [4, 8, 12]
... ]
... ),
... "z": 100}
>>>df1 = pd.DataFrame(dict1)
>>>df1
x y z
0 1 [2, 4, 6] 100
1 2 [3, 6, 9] 100
2 3 [4, 8, 12] 100
- 但隨后我將 Numpy ndarray (形狀 3, 3 )分配給 key
y,并嘗試從字典中創建一個 DataFrame 。我嘗試創建 DataFrame 錯誤的行。下面是我嘗試運行的代碼,以及我得到的錯誤(為了便于閱讀,在單獨的代碼塊中。)
- 代碼
???
>>>dict2 = {"x": [1, 2, 3],
... "y": np.array(
... [
... [2, 4, 6],
... [3, 6, 9],
... [4, 8, 12]
... ]
... ),
... "z": 100}
>>>df2 = pd.DataFrame(dict2) # see the below block for error
- 錯誤
???
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
d:\studies\compsci\pyscripts\study\pandas-realpython\data-delightful\01.intro.ipynb Cell 10' in <module>
1 # from a dicitionary
2 dict1 = {"x": [1, 2, 3],
3 "y": np.array(
4 [
(...)
9 ),
10 "z": 100}
---> 12 df1 = pd.DataFrame(dict1)
File ~\anaconda3\envs\dst\lib\site-packages\pandas\core\frame.py:636, in DataFrame.__init__(self, data, index, columns, dtype, copy)
630 mgr = self._init_mgr(
631 data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy
632 )
634 elif isinstance(data, dict):
635 # GH#38939 de facto copy defaults to False only in non-dict cases
--> 636 mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
637 elif isinstance(data, ma.MaskedArray):
638 import numpy.ma.mrecords as mrecords
File ~\anaconda3\envs\dst\lib\site-packages\pandas\core\internals\construction.py:502, in dict_to_mgr(data, index, columns, dtype, typ, copy)
494 arrays = [
495 x
496 if not hasattr(x, "dtype") or not isinstance(x.dtype, ExtensionDtype)
497 else x.copy()
498 for x in arrays
499 ]
500 # TODO: can we get rid of the dt64tz special case above?
--> 502 return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
File ~\anaconda3\envs\dst\lib\site-packages\pandas\core\internals\construction.py:120, in arrays_to_mgr(arrays, columns, index, dtype, verify_integrity, typ, consolidate)
117 if verify_integrity:
118 # figure out the index, if necessary
119 if index is None:
--> 120 index = _extract_index(arrays)
121 else:
122 index = ensure_index(index)
File ~\anaconda3\envs\dst\lib\site-packages\pandas\core\internals\construction.py:661, in _extract_index(data)
659 raw_lengths.append(len(val))
660 elif isinstance(val, np.ndarray) and val.ndim > 1:
--> 661 raise ValueError("Per-column arrays must each be 1-dimensional")
663 if not indexes and not raw_lengths:
664 raise ValueError("If using all scalar values, you must pass an index")
ValueError: Per-column arrays must each be 1-dimensional
為什么它在第二次嘗試中以錯誤結束,即使兩個陣列的維度相同?此問題的解決方法是什么?
uj5u.com熱心網友回復:
如果您仔細查看錯誤訊息并快速查看此處的源代碼:
elif isinstance(val, np.ndarray) and val.ndim > 1:
raise ValueError("Per-column arrays must each be 1-dimensional")
您會發現,如果字典值是一個 numpy 陣列并且具有多個維度作為您的示例,它會根據源代碼引發錯誤。因此,它與串列一起作業得很好,因為串列不超過一維,即使它是串列的串列。
lst = [[1,2,3],[4,5,6],[7,8,9]]
len(lst) # print 3 elements or (3,) not (3,3) like numpy array.
您可以嘗試使用 np.array([1,2,3]),它會起作用,因為維數為 1 并嘗試:
arr = np.array([1,2,3])
print(arr.ndim) # output is 1
如果需要在字典中使用 numpy 陣列,可以使用.tolist()將 numpy 陣列轉換為串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/448652.html
上一篇:為numpy陣列的子集賦值
