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
.
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.
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:
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’.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With