出现报错Traceback (most recent call last): File "D:\kelly\PycharmProjects\pythonProject7\7.2上证.py", line 15, in <module> r_df = pd.DataFrame({'r': r}) File "D:\python3.10\lib\site-packages\pandas\core\frame.py", line 664, in init mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager) File "D:\python3.10\lib\site-packages\pandas\core\internals\construction.py", line 493, in dict_to_mgr return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy) File "D:\python3.10\lib\site-packages\pandas\core\internals\construction.py", line 118, in arrays_to_mgr index = _extract_index(arrays) File "D:\python3.10\lib\site-packages\pandas\core\internals\construction.py", line 653, in _extract_index raise ValueError("Per-column arrays must each be 1-dimensional") ValueError: Per-column arrays must each be 1-dimensional怎么修改
时间: 2023-07-21 10:20:46 浏览: 329
这个报错提示是因为你传递给pd.DataFrame()函数的数据中存在多维数组,而DataFrame只接受一维数组作为列,因此需要将多维数组转换为一维数组后再传递给pd.DataFrame()函数。你可以尝试以下代码:
```python
import pandas as pd
r = [[1,2,3],[4,5,6],[7,8,9]] # 多维数组
r_flat = [item for sublist in r for item in sublist] # 将多维数组转换为一维数组
r_df = pd.DataFrame({'r': r_flat}) # 传递一维数组给pd.DataFrame()
print(r_df)
```
这样就可以将多维数组转换为一维数组并成功创建DataFrame。
阅读全文