You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用列表和现有DataFrame构建新DataFrame并按列插入列表元素

操作方法

方法1:原有空DataFrame赋值

如果你的DataFrame已经提前创建完成,直接按列索引对应赋值即可,长度不匹配的位置会自动填充NaN:

import pandas as pd

# 初始化你现有结构的空DataFrame
df = pd.DataFrame(columns=['column 1', 'column 2', 'column 3'])
# 待插入的列表数据
a = [['Master Vithal', ' Vithal Zubeida'], ['Firozshah Mistry', ' B Irani'], ['Grigor']]

# 按列顺序逐一赋值
for col_idx, col_name in enumerate(df.columns):
    df[col_name] = pd.Series(a[col_idx])

方法2:直接构造目标DataFrame

如果不需要保留原有DataFrame的其他内容,可以直接通过转置列表的方式快速生成:

import pandas as pd

a = [['Master Vithal', ' Vithal Zubeida'], ['Firozshah Mistry', ' B Irani'], ['Grigor']]
df = pd.DataFrame(a).T.set_axis(['column 1', 'column 2', 'column 3'], axis=1)

最终效果

两种方法得到的结果一致:

column 1column 2column 3
Master VithalFirozshah MistryGrigor
Vithal ZubeidaB IraniNaN

内容的提问来源于stack exchange,提问作者FafamKurac123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:06:04