簡體   English   中英

Pandas iloc復合切片每第n行

[英]Pandas iloc complex slice every nth row

我有一個14行的周期數據幀,即每條記錄有14行數據(均值,sdev等),我想為每條記錄重復提取第2,第4,第7和第9行(14行) )。 我的代碼是:

Mean_df = df.iloc[[1,3,6,8]::14,:].copy()

這不起作用

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [[1, 3, 6, 8]] of <class 'list'>

我從這里獲得了代碼的幫助,這對我來說非常有用,但不是多行選擇 - Pandas每隔n行

我可以提取幾個不同的切片並組合,但感覺可能有更優雅的解決方案。

有任何想法嗎?

使用:

df[np.isin(np.arange(len(df))%14,np.array([1,3,6,8]))]

你可以使用slicenp.r_的元組理解:

arr = np.arange(14*3)
slices = tuple(slice(i, len(arr), 14) for i in (1, 3, 6, 8))

res = np.r_[slices]

print(res)

array([ 1, 15, 29,  3, 17, 31,  6, 20, 34,  8, 22, 36])

在此示例中,使用1::14索引數據幀行等效於使用slice(1, df.shape[0], 14)進行索引。

這是非常通用的,您可以定義任何切片對象元組並傳遞給np.r_

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM