Search code examples
python-3.xpandasdataframecontains

Get a vlaue from a column based on another column


Lets say I have a data frame like this one:

   id       name             folder 
0   4     test_policy_1       testing
1   5     loop_foot_1         final
2   6     column_case_1       testing 
3   7     line_push_1         final

I want to check for example if the name contains "case" to return id 6.

I tried this one:

for i in df.index:
        if "case" in df['name'][i]:
            print( df['id'][i])
        else:
            print("File not found")

and it is showing me this:

File not found
File not found
6
File not found

How can I modify this code to only get the id 6?


Solution

  • this gives you a single value, but if you drop the .iat[0] you'll get the dataframe, in case you have multiple rows meeting your condition

    df[df.name.str.contains('case')]['id'].iat[0]
    

    this will give you a list of ids

    df[df.name.str.contains('case')]['id'].tolist()