RustyShackleford
RustyShackleford

Reputation: 3677

How to search column name by partial string match and replace values in the column by dictionary?

I need to search for column names based on partial strings and replace the column values from that of dictionary.

I am searching for partial column name string like so:

df.loc[df.columns.str.contains('column na')]

which works fine.

Now I want to replace values in the column that has been identified by partial string but with a dictionary values which I can do like this only on full column names:

di = {'a': 0, 'b': 1,'c':2,'d':3 }

df['column name'].replace(di,inplace=True)

How do I combine partial string search with replace?

I have tried this:

df = df.loc[df.columns.str.contains('column na')].replace(di, inplace=True)

but this replaces the entire df with the message NoneType object of builtins module

edit:

current df looks like this:

column1-adfas         column2-zdfsdf
a                            b

I want to be able to search and replace values from partial column name string like so:

column1-adfas         column2-zdfsdf
0                            1

Upvotes: 1

Views: 413

Answers (1)

Umar.H
Umar.H

Reputation: 23099

If I understand, we can leverage .map however it only applies to series, so lets use an apply function, we can filter columns using filter

cols = df.filter(like='column').columns
df[cols] = df[cols].apply(lambda x : x.map(di))

print(df)
     column1-adfas  column2-zdfsdf
0              0               1

Upvotes: 2

Related Questions