如何将通过df.iterrows存入列表的多个Series转换为DataFrame?
把Series列表转回原结构DataFrame的几种方法
方法1:直接用pd.DataFrame()构造
最简单的方式就是把存Series的列表直接传给pd.DataFrame()构造器,它会自动对齐所有Series的列索引,直接还原出和原df一致的结构:
import pandas as pd # 假设tmp_list是你已有的Series列表 new_df = pd.DataFrame(tmp_list) print(new_df)
输出结果:
firstname age lastname 0 Sally 50 a1 1 Mary 40 b1 2 John 30 c1
方法2:用pd.concat()拼接
如果需要更灵活的拼接控制(比如处理索引、自定义拼接逻辑),可以用pd.concat(),两种写法都能实现需求:
# 方式1:按列拼接后转置 new_df = pd.concat(tmp_list, axis=1).T # 方式2:将每个Series转为单行DataFrame后拼接 new_df = pd.concat([s.to_frame().T for s in tmp_list], ignore_index=True)
两种写法都能得到和原DataFrame完全一致的结果。
额外提示
- 若列表中Series的列数不一致,这些方法会自动对齐列,缺失的位置会填充
NaN - 如果不需要保留原Series的
Name作为行索引,可以添加ignore_index=True参数重置索引,比如pd.DataFrame(tmp_list, ignore_index=True)
内容的提问来源于stack exchange,提问作者jkim
相关产品推荐
相关产品推荐

