首页 > 解决方案 > 在多个熊猫列中按元素合并 np.array

问题描述

我有一个 pandas 数据框,其中有几列的值为 np.array,我想将这些 np.arrays 合并为一个基于数组元素的行。

例如

 col1          col2        col3 
[2.1, 3]      [4, 4]      [2, 3] 
[4, 5]        [6, 7]      [9, 9] 
[7, 8]        [8, 9]      [5, 4] 
...             ...         ...

预期结果:

col_f
[2.1, 3, 4, 4, 2, 3] 
[4, 5, 6, 7, 9, 9] 
[7, 8, 8, 9 5, 4] 

...........

我使用一种 for 循环来实现它,但只是想知道是否有更优雅的方式来实现它。

下面是我的for循环代码:

f_vector = []
for i in range(len(df.index)):
    vector = np.hstack((df['A0_vector'][i], items_df['A1_vector'][i], items_df['A2_vector'][i], items_df['A3_vector'][i], items_df['A4_vector'][i], items_df['A5_vector'][i])) 
    f_vector.append(vector)
X = np.array(f_vector)

标签: pythonpandasnumpy

解决方案


您可以将numpy.concatenate与沿轴 = 1 的应用一起使用:

import numpy as np
df['col_f'] = df[['col1', 'col2', 'col3']].apply(np.concatenate, axis=1)

如果这些是列表而不是 np.arrays,则+运算符会起作用:

df['col_f'] = df['col1'] + df['col2'] + + df['col3']

注意:在下面的评论线程后编辑。


推荐阅读