Alok Sharma
Alok Sharma

Reputation: 115

Access column of dataframe by index for validation

Below piece of code works perfectly fine for column name 'AType'

df=df[df['AType'].isin(['P','C'])]     
        

but instead of mentioning as df['AType'] can I do above validation as column number

df=df[df.columns[7].isin(['P','C'])]

It is raising error

 df=df[df.columns[7].isin(['P','C'])]
 AttributeError: 'str' object has no attribute 'isin'

Need to do column validation on basis of column number

Upvotes: 1

Views: 105

Answers (2)

ALollz
ALollz

Reputation: 59549

.iloc is the integer-location based indexer.

df = df[df.iloc[:, 7].isin(['P','C'])]  

Upvotes: 2

anky
anky

Reputation: 75080

you need to pass the key you receive after df.columns[7] to the dataframe to obtain the series to be able to use isin

df=df[df[df.columns[7]].isin(['P','C'])]

The code:

df.columns[7]

This returns a string value. Whereas

df[df.columns[7]]

Returns a series which has the attribute isin

Upvotes: 2

Related Questions