1

So I need to extract a cell value for a row whose another column matches a pattern.

I have the following Dataframe df:

id    A               B           C
0  2018-A4-X     some_name  2018-09-02
1  2018-A3-X     some_name  2018-05-13
2  2018-A2-X     some_name  2018-02-18
3  2018-A1-X     some_name  2017-11-26

I want to extract the column C's value where column A's value contains string 'A4'.

I tried to do like this but it gives 'KeyError: True'.

a4 = df.loc['A4' in str(df['id']), 'C'].iloc[0]

So my output in the above case should be 2018-09-02

Atihska
  • 4,803
  • 10
  • 56
  • 98

1 Answers1

2

Use:

print(df.loc[df['A'].str.contains('A4'),'C'].item())

Output:

2018-09-02

Use loc, then str.contains to 'A' column to see if 'A4' is in it, if it is, get 'C' column, and use item to get the value.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114