简体   繁体   English

使用切片和列表索引数据帧

[英]Indexing a data frame using slicing and lists

Is it possible to index a data frame using something like 是否可以使用类似的方法索引数据帧

df[[0:12, 14, 19], [0:4 , 6]]

where I want to get rows 0 - 11, 14, 19 and columns 0 - 4, 6. Using iloc I haven't been able to combine slicing along with specific row or column numbers. 我想获得0-11、14、19行和0-4、6列。在使用iloc时,我无法将切片与特定的行号或列号结合在一起。

将切片和列表一起使用可能是一种更正式的方法,但是将切片转换为列表并将其与单个列/行的列表组合起来可能是最简单的方法。

df.iloc[range(0,12) + [14, 19], range(0,5) + [6]]

It would not allow indexing the dataframe like that, but you can create two lists. 它不允许像这样索引数据框,但是您可以创建两个列表。 One list will have the indeces for the rows that you want and the other for the columns. 一个列表将包含所需行的索引,另一列表将包含列的索引。 Then, you can use the loc function to get your result. 然后,您可以使用loc函数获得结果。

The lists are created with the specifics in the example. 将使用示例中的详细信息创建列表。 List comprehension was used for the successive numbers and a list for the individual numbers outside of a range. 列表理解用于连续数字,列表用于范围之外的单个数字。

list_of_rows=[i for i in range(12)]+[14,19]
list_of_columns=[i for i in range(4)]+[6]
df1=df.loc[list_of_rows,list_of_columns]

I think you can seperate the iloc comand in row 0-11 and column 0-4, for example 我认为您可以在第0-11行和第0-4列中分隔iloc comand

data.iloc[0:14, 0:4]

and then do the same for row 0-11 and column 6 and so on, afterwards you can combine the different ilocs 然后对第0-11行和第6列进行相同操作,依此类推,然后您可以组合不同的iloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM