Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数组作为列附加到原始数据帧_Python_Pandas - Fatal编程技术网

Python 如何将数组作为列附加到原始数据帧

Python 如何将数组作为列附加到原始数据帧,python,pandas,Python,Pandas,我有一个如下所示的数据框: x_1 x_2 x_3 x_combined 0 1 0 [0,1,0] 1 0 1 [1,0,1] 1 1 0. [1,1,0] 0 0 1 [0,0,1] 然后,我使用np.mean(df['x_combined'],axis=0)计算每个维度的质心,并得到 数组([0.5,0.5,0.5]) 现在如何将其作为第五列追加回原始DF,并使每行具有相同的值?应该是这样的: x_1 x_2 x_3 x_combined

我有一个如下所示的数据框:

x_1 x_2 x_3 x_combined
0   1    0  [0,1,0]
1   0    1  [1,0,1]
1   1    0. [1,1,0]
0   0    1  [0,0,1]
然后,我使用
np.mean(df['x_combined'],axis=0)计算每个维度的质心,并得到

数组([0.5,0.5,0.5])

现在如何将其作为第五列追加回原始DF,并使每行具有相同的值?应该是这样的:

x_1 x_2 x_3  x_combined  centroid
0   1    0  [0,1,0]     [0.5, 0.5, 0.5]
1   0    1  [1,0,1]     [0.5, 0.5, 0.5]
1   1    0. [1,1,0]     [0.5, 0.5, 0.5]
0   0    1  [0,0,1]     [0.5, 0.5, 0.5]
这也适用于:

df = pd.DataFrame({
    'x_1': [0, 1, 1, 0],
    'x_2': [1, 0, 1, 0],
    'x_3': [0, 1, 0, 1],
    'x_combined': [np.array([0, 1, 0]), np.array([1, 0, 1]),
                   np.array([1, 1, 0]), np.array([0, 0, 1])]
})

a = np.mean(df['x_combined'], axis=0)  # or a = df['x_combined'].mean(axis=0)
df['centroid'] = [a]*len(df)