pandas 如何将条件应用于熊猫 iloc
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50292460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply a condition to pandas iloc
提问by Googlebot
I select columns 2 - end
from a pandas DataFrame with iloc
as
我选择列2 - end
从Pandas数据帧与iloc
作为
d=c.iloc[:,2:]
now how can I apply a condition to this selection? For example, if column1==1
.
现在如何将条件应用于此选择?例如,如果column1==1
.
回答by jezrael
You can use DataFrame.iloc
if need filter first column select by position, :
means here select all rows:
您可以使用DataFrame.iloc
if 需要过滤第一列按位置选择,:
表示这里选择所有行:
c[c.iloc[:, 0] == 1]
Sample:
样品:
c = pd.DataFrame({'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')})
print (c)
A B C D E F
0 a 4 7 1 5 a
1 b 5 8 3 3 a
2 c 4 9 5 6 a
3 d 5 4 7 9 b
4 e 5 2 1 2 b
5 f 4 3 0 4 b
df = c[c.iloc[:, 3] == 1]
print (df)
A B C D E F
0 a 4 7 1 5 a
4 e 5 2 1 2 b
回答by piRSquared
This is referred to as mixed indexing in that you want to index by boolean results in rows and position in columns. I'd use loc
in order to take advantage of boolean indexing for the rows. But that implies that you need column names values for the column slice.
这被称为混合索引,因为您希望按行中的布尔结果和列中的位置进行索引。我会使用loc
以利用行的布尔索引。但这意味着您需要列切片的列名值。
d.loc[d.column1 == 1, d.columns[2:]]
If your column names are not unique then you can resort to the dreaded chained index.
如果您的列名不是唯一的,那么您可以求助于可怕的链式索引。
d.loc[d.column1 == 1].iloc[:, 2:]
What might also be intuitive is to use query
afterwards:
可能也很直观的是query
之后使用:
d.iloc[:, 2:].query('column1 == 1')