numpy.repeat 重复数组的元素(可用于数组的广播)

您所在的位置:网站首页 python字符串重复n次输出 numpy.repeat 重复数组的元素(可用于数组的广播)

numpy.repeat 重复数组的元素(可用于数组的广播)

2023-12-21 13:41| 来源: 网络整理| 查看: 265

有时候,我们需要根据某列的分成多列,那么,有些列就需要重复多次,比如说:

newvalues=np.dstack((np.repeat(t.reportno.values,list(map(len,t.data_list.values))),np.concatenate(t.data_list.values))) pd.DataFrame(data=newvalues[0],columns=['reportno','data_list']) #看看这个repeat list(map(len,t.data_list.values)) #[4, 4, 4, 18, 4, 24, 13, 4, 64, 24, 18, 4, 7, 13, 17]

 

numpy.repeat()

我们下面看一下函数

numpy.repeat(a, repeats, axis=None) 参数:

a:array_like ,需要重复的数据

repeats:int or array of ints,每个元素的重复次数。可以是list,比如上面的

axis:int, 可选,axis=None(默认)时候就会flatten当前矩阵,实际上就是变成了一个行向量,axis=0,沿着y轴复制,实际上增加了行数,axis=1,沿着x轴复制,实际上增加列数

例子: #3重复4次 np.repeat(3, 4) #array([3, 3, 3, 3]) #重复2次,注意不是1234,1234 x = np.array([[1,2],[3,4]]) np.repeat(x, 2) #array([1, 1, 2, 2, 3, 3, 4, 4]) #增加列数 np.repeat(x, 3, axis=1) ''' array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]) ''' #增加行数,1相当于原来的值,重复一次就是原来的值 np.repeat(x, [1, 2], axis=0) ''' array([[1, 2], [3, 4], [3, 4]]) '''

官网:https://numpy.org/doc/stable/reference/generated/numpy.repeat.html

 

pandas.Series.repeat

我们一般这样使用

df.col.repeat(n)

其中n和上面的repeats参数一样,还有axis不需要填

更多信息,请查看官网:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.repeat.html?highlight=repeat#pandas.Series.repeat

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3