如何用两个等长列表创建指定结构的Pandas DataFrame?
问题描述
我有两个长度相同的列表(各含48个元素),希望创建一个DataFrame,将其中一个列表作为列名,另一个列表作为对应列的值。示例如下:
list_1 = ["A", "B", "C", "D", "E"]
list_2 = [1, 2, 3, 4, 5]
期望得到的DataFrame结构:
| A | B | C | D | E |
|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 |
尝试用pandas实现时写了如下代码:
dataframe = pd.DataFrame(data=data, columns=fields)
但触发了错误:
Output exceeds the size limit. Open the full output data in a text editor --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[83], line 1 ----> 1 dataframe_maybe = pd.DataFrame(data=data, columns=fields) 3 dataframe_maybe File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\frame.py:762, in DataFrame.__init__(self, data, index, columns, dtype, copy) 754 mgr = arrays_to_mgr( 755 arrays, 756 columns, (...) 759 typ=manager, 760 ) 761 else: --> 762 mgr = ndarray_to_mgr( 763 data, 764 index, 765 columns, 766 dtype=dtype, 767 copy=copy, 768 typ=manager, 769 ) 770 else: 771 mgr = dict_to_mgr( 772 {}, ... 418 passed = values.shape 419 implied = (len(index), len(columns)) --> 420 raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}") ValueError: Shape of passed values is (48, 1), indices imply (48, 48)
请问我遗漏了什么?有没有更简便的实现方法?
问题分析与解决
错误原因
报错核心是数据形状不匹配:将list_2作为data传入时,pandas默认将其解析为48行1列的结构,但你指定了48个列名,pandas期望的是48行48列的数据,两者形状冲突导致ValueError。
简便实现方法
以下三种方式都能快速得到目标DataFrame:
方法1:字典推导构造
直接将两个列表打包成键值对,每个列对应一个单行列表:
import pandas as pd list_1 = ["A", "B", "C", "D", "E"] list_2 = [1, 2, 3, 4, 5] df = pd.DataFrame({col: [val] for col, val in zip(list_1, list_2)})
方法2:二维数组转置
将list_2包装成二维数组(1行N列),再指定列名:
df = pd.DataFrame([list_2], columns=list_1)
方法3:Series转置构造
先构造Series,再转置为DataFrame:
s = pd.Series(list_2, index=list_1) df = s.to_frame().T
内容的提问来源于stack exchange,提问作者xerxes
相关产品推荐
相关产品推荐

