user10508414
user10508414

Reputation:

How to find the row whcih contains from the pivot table

My DF is below. FInd the rows contains

gender  FEMALE  MALE    OTHER
AGE         
[15-20]     0   1   0
[25-30]     0   1   0

df_1[df_1['AGE'].str.contains("15-20")]

Expected Out

gender  FEMALE  MALE    OTHER
    AGE         
    [15-20]     0   1   

Upvotes: 0

Views: 37

Answers (2)

Andy L.
Andy L.

Reputation: 25239

As in your sample, its index AGE looks like a list of string to me. It is not a simple string, so checking on straight string "15-20" won't work.

You may try this:

df_out = df[df.index.map(lambda x: x[0] == "15-20")]

###or 

df_out = df[df.index.map(lambda x: "15-20" in x)]

Out[132]:
gender   FEMALE  MALE  OTHER
AGE
[15-20]       0     1      0

Or using str accessor to get first element

df_out = df[df.index.str[0] ==  "15-20"]

Out[133]:
gender   FEMALE  MALE  OTHER
AGE
[15-20]       0     1      0

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19947

You can use str.contains:

df.loc[df.index.str.contains("15-20")]

Or as suggested by @anky_91, the loc operation can be removed:

df[df.index.str.contains("15-20")]

Upvotes: 1

Related Questions