python numpy concatenate 实现列表的拼接

举报
lu_zhishen 发表于 2021/03/23 16:04:31 2021/03/23
【摘要】 numpy.concatenate((a1, a2, ...), axis=0)Join a sequence of arrays along an existing axis.Parameters:a1, a2, ... : sequence of array_likeThe arrays must have the same shape, except in the dimension ...

numpy.concatenate((a1, a2, ...), axis=0)

Join a sequence of arrays along an existing axis.

Parameters:

a1, a2, ... : sequence of array_like

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

axis : int, optional

The axis along which the arrays will be joined. Default is 0.

Returns:

res : ndarray

The concatenated array.

以上内容复制于:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.concatenate.html

concatenate: 可以实现类似array的拼接,参数(a1,a2)必须要有相同的shape,如果是一维数组那么a1,a2 都要是一维数组,每个数组长度不限制。如果都是二维,那么对应维度的长度要相等

以下代码会报错:提示l1 是2维,l2是一维

l1=[['q1','q2','q3'],['e2','e3','d4']]
l2=['q2','q3']

con = np.concatenate((l1,l2))

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

以下代码也会报错

l1=[['q1','q2','q3'],['e2','e3','d4']]
l2=[['q2','q3'],['q2','q3']]

con = np.concatenate((l1,l2))

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 2

以下代码则不报错

import numpy as np

l1=[['q1','q2','q3'],['e2','e3']]
l2=[['q2','q3','d4'],['e2','e3']]
con = np.concatenate((l1,l2))

print(con)

如果axis=1 则是另外一个方向的合并,需要维度大小相等,各列表长度也相等

再dataframe 里面的使用,可以将一个列表值拆分成多行

pd.DataFrame({'姓名':df.姓名.repeat(df.课程.str.len()),'课程':np.concatenate(df.课程.values)})

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。