如何在Python中将给定列表数据读取并转换为pandas DataFrame
将Python列表转换为Pandas DataFrame
操作步骤
- 先确认已安装pandas库,未安装的话执行命令:
pip install pandas - 直接使用
pd.DataFrame()构造函数传入目标列表,即可完成转换。
完整代码示例
import pandas as pd # 定义你的列表数据 raw_data = [ {"col1": "", "col2": "xx", "col3": "00001-1", "col4": "", "col5": "", "col6": "xx"}, {"col1": "1", "col2": " aaa ", "col3": "00001-3", "col4": "0", "col5": "", "col6": "xx - abc"}, {"col1": "1", "col2": "xx zzz", "col3": "00001-4", "col4": "0", "col5": "", "col6": "xx yyy"} ] # 转换为DataFrame df = pd.DataFrame(raw_data) # 查看转换后的结果 print(df)
补充说明
- 列表中的每个字典对应DataFrame的一行,字典的键会自动作为列名
- 若希望保留原始空字符串而非自动转为
NaN,可以指定数据类型:df = pd.DataFrame(raw_data, dtype=str)
内容的提问来源于stack exchange,提问作者kmr
相关产品推荐
相关产品推荐

