You need to enable JavaScript to run this app. 如何将Numpy数组作为新列追加到原有Pandas DataFrame中
优惠活动
大模型
产品
解决方案
定价
更多

如何将Numpy数组作为新列追加到原有Pandas DataFrame中

实现方案

你已经通过np.mean(df['x_combined'], axis=0)计算得到质心数组后,只需将该数组作为单个元素,重复填充到DataFrame的每一行即可,推荐两种实现方式:

方式1:列表重复赋值(性能更高,适合大体积数据表)

先将numpy数组转为普通列表,再构造与DataFrame行数等长的列表赋值给新列:

import numpy as np
import pandas as pd

# 计算质心
centroid = np.mean(df['x_combined'], axis=0)
# 追加centroid列
df['centroid'] = [centroid.tolist()] * len(df)

方式2:apply批量赋值(写法更简洁,适合小体积数据表)

通过apply方法给每一行返回同一个质心值:

centroid = np.mean(df['x_combined'], axis=0)
df['centroid'] = df.apply(lambda _: centroid.tolist(), axis=1)

注意事项

不要直接写df['centroid'] = centroid,pandas会默认将长度为3的质心数组匹配DataFrame的行长度(你的示例为4行),会触发长度不兼容的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 01:45:03