熊猫iloc每第n行复数切片

时间:2018-08-17 14:29:48

标签: python pandas dataframe indexing slice

我在第14行有一个周期性的数据帧,即每条记录有14行数据(均值,sdev等),我想为每条记录重复提取第二行,第四行,第七行和第九行(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 every nth row

我可以提取几个不同的切片并合并,但是感觉可能有一个更优雅的解决方案。

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

使用:

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

答案 1 :(得分:2)

您可以对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_