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

如何为Pandas DataFrame的每一列追加固定一维数组?

如何将一维数组追加到Pandas DataFrame的每一列?

问题场景

现有如下Pandas DataFrame和一维数组:

import pandas as pd

df = pd.DataFrame([
    ['234', '434', '471', '4744', '477'],
    ['2.4', '2.4', '2.4'],
])
df.columns = ['col 1', 'col 2', 'col 3', 'col 4', 'col 5']

oneD_array = [1, 0, 0, 1, 2, 3]

需要将oneD_array中的每个元素追加到DataFrame的所有列中,最终得到每列都新增数组对应元素行的结果。

解决方案

方法一:使用pd.concat(推荐)

先将一维数组转换为与原DataFrame列数一致的新DataFrame,再与原DataFrame纵向拼接:

# 生成包含数组元素的新行,每行的所有列值都为当前数组元素
new_rows = pd.DataFrame([[val]*len(df.columns) for val in oneD_array], columns=df.columns)
# 拼接原DataFrame和新行,重置索引
result_df = pd.concat([df, new_rows], ignore_index=True)

# 查看结果
print(result_df)

方法二:使用df.append(已弃用,仅作参考)

若使用旧版Pandas,可通过构造字典列表的方式追加行,但该方法已在Pandas 2.0+中被标记为弃用:

# 构造每个数组元素对应的行字典(所有列值为当前元素)
rows_to_append = [{col: val for col in df.columns} for val in oneD_array]
# 追加行并重置索引
result_df = df.append(rows_to_append, ignore_index=True)

输出结果

运行代码后将得到符合预期的DataFrame:

col 1 col 2 col 3 col 4 col 5
0   234   434   471  4744   477
1   2.4   2.4   2.4   2.4   2.4
2     1     1     1     1     1
3     0     0     0     0     0
4     0     0     0     0     0
5     1     1     1     1     1
6     2     2     2     2     2
7     3     3     3     3     3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:15:42