Mdhale Mdhale - 2 months ago 17
Python Question

Looking up Pandas dataFrame

I have created a data frame by reading a text file. I am interested in knowing if few values exist in a particular column and if they do, I want to print the entire row.

This is my input file(analyte_map.txt):

Analyte_id mass Intensity
A34579 101.2 786788
B12345 99.2 878787
B943470 103.89 986443
C12345 11.2 101


This is my code:

import pandas as pd
map_file="analyte_map.txt"
array=['A34579','B943470','D583730']
analyte_df=pd.read_table(map_file,sep="\t")
for value in array:
if analyte_df.lookup([value],['Analyte_id']):
print '%s\t%s'%(analyte_df['mass'],analyte_df['Intensity'])

Answer

You can use boolean indexing with isin:

array=['A34579','B943470','D583730']
print (df[df.analyte_id.isin(array)])
  analyte_id    mass  Intensity
0     A34579  101.20     786788
2    B943470  103.89     986443

Also if need only some columns use ix:

array=['A34579','B943470','D583730']
print (df.ix[df.analyte_id.isin(array), ['mass','Intensity']])
     mass  Intensity
0  101.20     786788
2  103.89     986443