zoukankan      html  css  js  c++  java
  • numpy.repeat 重复数组的元素(可用于数组的广播)

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

    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

  • 相关阅读:
    深拷贝与浅拷贝
    图片旋转插件
    promise 小抄
    github fork项目更改后与原作者同步更新
    eslint 的配置
    css规范
    Object类
    BigIntager
    System类
    Math类和Random类
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/14188921.html
Copyright © 2011-2022 走看看