繁体   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