python - 在多个熊猫列中按元素合并 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)
解决方案
您可以将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']
注意:在下面的评论线程后编辑。
推荐阅读
- android-sqlite - 如何按整数查询 SQLite?
- reactjs - 未捕获的不变违规:无法在未安装的组件上找到节点。使用“@material-ui/core”:“3.9.3”
- javascript - 为复合组件添加默认道具
- javascript - 数据中的变量不断恢复为真
- javascript - JavaScript 中的继承
- r - 如何在没有图形设备的机器上保存图像?
- r - 由于 rbind 错误,R Markdown 不编织
- sql - 更改表 msdb.dbo.sysjobschedules 中的 schedule_id 的问题
- python - 有没有更好/更干净的方法来格式化这个脚本
- angular - 自定义日期范围内联选择器