Monica
Monica

Reputation: 1070

Selecting a subset of a Pandas DataFrame

I have the following DateFrame:

 record_id  month  day  year  plot species  sex  wgt 
    33320      33321      1   12  2002     1      DM    M   44
    33321      33322      1   12  2002     1      DO    M   58
    ...          ...      ...  ...  ...    ...    ...   ... ...  

I want to display columns from year to wgt with values equal 27. I have done it on two lines:

df_slice =  df[df.year == 27]
df_slice = df_slice.ix[:,'year':]

Is there any way to reduce it to one line?

Upvotes: 1

Views: 79

Answers (2)

jezrael
jezrael

Reputation: 862511

You can use ix:

print (df.ix[df.year == 27, 'year':])

Sample (value 2001 was added):

print (df)
   record     id  month  day  year  plot species sex  wgt
0   33320  33321      1   12  2001     1      DM   M   44
1   33321  33322      1   12  2002     1      DO   M   58

print (df.ix[df.year == 2001, 'year':])
   year  plot species sex  wgt
0  2001     1      DM   M   44

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81594

Is there any way to reduce it to one line?

You can easily combine the 2 lines into 1:

df_slice = df[df.year == 27].ix[:,'year':]

Upvotes: 2

Related Questions