How to set a value to all cells that are equal to a certain string

Viewed 32

I have a dataframe like so:

import pandas as pd
mydict = {0:['help', 'Hello-123random'], 1:['Hello&$%^','me'], 2: ['plz','lmfao']}
df = pd.DataFrame.from_dict(mydict, orient='index')

df

I am trying to replace every cell that contains 'Hello' with a 1 and everything else with 0. I have the following code:

cols = df.columns.to_list()
for col in cols:    
    for j in range(len(df)):
        try:
            if df[col][j][:5] == 'Hello':
                df[col][j] = 1
            else:
                df[col][j] = 0
        except:
            df[col][j] = 0

This is functional and returns the below dataframe. However, this code is getting some errors with a bigger dataset and I feel like this could be done in 1 line. Does anyone know a solution?

df desired

1 Answers

Try:

df.astype(str).apply(lambda col: col.str.contains("Hello", case=False)).astype(int)

   0  1
0  0  1
1  1  0
2  0  0
Related