How can I find special letters in multiple columns of dataframe?

Question:

I’m trying to find special letter to check if replace has been done correctly.

df = pd.read_excel(io = "mydata.xlsx", sheet_name = 'Sheet1', index_col = 0)
df

header = df.select_dtypes(['object']).columns # to get the str type columns only
df[header].apply(lambda x: x.str.replace(pat=r'[^w]', repl=r'', regex=True)) # and replace them with black ''

to see columns with special letter:

df_header = df[header]
df_test2 = df_header[['PCETC_DTL','WARNSPEAK4DTL','WARNBEHAV4DTL','WARNEMOTION4DTL','WARNSIGN_DTL','EVENT_DTL','EVENT_DTL_2']]
df_test2[df_test2.apply(lambda x: x.str.contains('w', na=False))]

and I got the result:

PCETC_DTL   WARNSPEAK4DTL   WARNBEHAV4DTL   WARNEMOTION4DTL WARNSIGN_DTL    EVENT_DTL   EVENT_DTL_2
EXCLUDE                         
1_3 NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ...
1_3 NaN NaN NaN NaN NaN NaN NaN
1_3 NaN NaN NaN NaN NaN NaN NaN
1_3 NaN NaN NaN NaN NaN NaN NaN
1_3 NaN NaN NaN NaN NaN NaN NaN
1_3 NaN NaN NaN NaN NaN NaN NaN
104959 rows × 7 columns

How can I see rows with ‘w’ only?

Asked By: Joshua Chung

||

Answers:

You can aggregate the booleans per row with any to only select rows with at least one w:

df_test2[df_test2.apply(lambda x: x.str.contains('w', na=False)).any(1)]

If you want to filter both rows and columns:

df2 = df_test2.apply(lambda x: x.str.contains('w', na=False))

df_test2.loc[df2.any(1), df2.any()]
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.