Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a condition to pandas iloc

I select columns 2 - end from a pandas DataFrame with iloc as

d=c.iloc[:,2:]

now how can I apply a condition to this selection? For example, if column1==1.

like image 983
Googlebot Avatar asked May 11 '18 12:05

Googlebot


People also ask

What is The ILOC method in pandas?

The iloc method enables you to “locate” a row or column by its “integer index.” We use the numeric, integer index values to locate rows, columns, and observations. i nteger loc ate. iloc. Get it? The syntax of the Pandas iloc isn’t that hard to understand, especially once you use it a few times. Let’s take a look at the syntax.

How to apply if condition with Lambda in pandas?

2) Applying IF condition with lambda Let us create a Pandas DataFrame that has 5 numbers (say from 51 to 55). Let us apply IF conditions for the following situation. If the particular number is equal or lower than 53, then assign the value of ‘True’. Otherwise, if the number is greater than 53, then assign the value of ‘False’. Syntax:

How do I assign a value if condition is met in pandas?

df.loc [df [‘column name’] condition, ‘new column name’] = ‘value if condition is met’ Let us create a Pandas DataFrame that has 5 numbers (say from 51 to 55). Let us apply IF conditions for the following situation. If the particular number is equal or lower than 53, then assign the value of ‘True’.

What is the difference between iloc () and Loc () in SQL Server Dataframe?

The sub DataFrame can be anything spanning from a single cell to the whole table. iloc () is generally used when we know the index range for the row and column whereas loc () is used on a label search. The below example shows the use of both of the functions for imparting conditions on the Dataframe.


1 Answers

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.

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:

d.iloc[:, 2:].query('column1 == 1')
like image 97
piRSquared Avatar answered Sep 27 '22 20:09

piRSquared