Python list or pandas dataframe 任意索引和切片

Python list or pandas dataframe arbitrary indexing and slicing

我在工作中广泛使用了 R 和 Python,有时我会混淆它们之间的语法。

在 R 中,如果我只想根据数据集的 一些 特征创建模型,我可以这样做:

subset = df[1:1000, c(1,5,14:18,24)]

这需要前 1000 行(是的,R 从索引 1 开始),并且需要第 1、5、14 through第18、24列。

我曾尝试对 slicerange 和类似功能进行任意组合,但无法复制这种灵活性。最后,我只是列举了所有的值。

如何在 Python 中完成?

Pick an arbitrary subset of elements from a list, some of which are selected individually (as in the commas shown above) and some selected sequentially (as in the colons shown above)?

您可以在 pandas 中使用 iloc 进行整数索引:

df.iloc[0:10000, [0, 4] + range(13,18) + [23]]

正如@root 所说,在 Python 3 中,您需要将 range() 显式转换为 df.iloc[0:10000, [0, 4] + list(range(13,18)) + [23]]

列表

试试这个,第一个方括号过滤器。第二组方括号切片。

df[[0,4]+ range(13,18)+[23]][:1000]

index_tricks 的文件中,numpy 定义了一个 class 实例,它使用 r_ 方法将标量和切片转换为枚举列表:

In [560]: np.r_[1,5,14:18,24]
Out[560]: array([ 1,  5, 14, 15, 16, 17, 24])

它是一个带有__getitem__方法的实例,所以它使用了索引语法。它将 14:18 扩展为 np.arange(14,18)。它还可以使用 linspace.

扩展值

所以我认为你会重写

subset = df[1:1000, c(1,5,14:18,24)]

作为

df.iloc[:1000, np.r_[0,4,13:17,23]]