Index of element

Question:

I have a dataframe with 100 rows and 10 columns.Now I know a value in column A and would like to know the value of column B in the same row.Could some one tell me the way please

I tried using the index method as idx=df["column A"].index("value")
df[idx]["column B"] but showing error

Asked By: mechanics

||

Answers:

You can do it in many ways, the purpose of pandas is to help you with managing data. For example:

import pandas as pd
import numpy as np

#Generating 100 rows, 10-column random data
df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)), columns=list('ABCDEFGHIJ'))

#only return A and B column
print(df[["A","B"]])

#Return the B column only if the value of column A greater than 50
print(df.loc[df["A"]>50,["B"]])

#Return column B only for the range 5 to 10
print(df.iloc[5:10]["B"])

#Return columns A, and B when the value of A is between 50 to 60
print(df.loc[df['A'].between(50, 60),["A","B"]])

#Return columns A and B only for five first and last rows
print(df.loc[np.r_[0:5, 95:100], ["A","B"]])

You can do many more; check the doc of loc and iloc for more detail

Answered By: Niyaz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.