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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM