Neil
Neil

Reputation: 211

search for string in pandas row

How can I search through the entire row in a pandas dataframe for a phrase and if it exist create a new col where says it says 'Yes' and what columns in that row it found it in? I would like to be able to ignore case as well.

Upvotes: 1

Views: 192

Answers (1)

hellpanderr
hellpanderr

Reputation: 5896

You could use Pandas apply function, which allows you to traverse rows or columns and apply your own function to them.

For example, given a dataframe

+--------------------------------------+------------+---+
|               deviceid               | devicetype | 1 |
+--------------------------------------+------------+---+
| b569dcb7-4498-4cb4-81be-333a7f89e65f | Google     | 1 |
| 04d3b752-f7a1-42ae-8e8a-9322cda4fd7f | Android    | 2 |
| cf7391c5-a82f-4889-8d9e-0a423f132026 | Android    | 3 |
+--------------------------------------+------------+---+

Define a function

def pr(array, value):
    condition = array[array.str.contains(value).fillna(False)].index.tolist()
    if condition:
        ret = array.append(pd.Series({"condition":['Yes'] + condition}))
    else:
        ret = array.append(pd.Series({"condition":['No'] + condition}))
    return ret

Use it

df.apply(pr, axis=1, args=('Google',))

+---+--------------------------------------+------------+---+-------------------+
|   |               deviceid               | devicetype | 1 |     condition     |
+---+--------------------------------------+------------+---+-------------------+
| 0 | b569dcb7-4498-4cb4-81be-333a7f89e65f | Google     | 1 | [Yes, devicetype] |
| 1 | 04d3b752-f7a1-42ae-8e8a-9322cda4fd7f | Android    | 2 | [No]              |
| 2 | cf7391c5-a82f-4889-8d9e-0a423f132026 | Android    | 3 | [No]              |
+---+--------------------------------------+------------+---+-------------------+

Upvotes: 1

Related Questions