coelidonum
coelidonum

Reputation: 543

Change values in column if the correct ones are present in list (Pandas)

I have a list of 'right' sizes.

list_sizes=['YT trueview', 'YT TRUEVIEW something', 'YT pre-roll', 'YT bumper', 'YT preferred pre-roll', 'YT preferred bumper', 'YT masthead','Advertorials', 'Editorial Content']

And a column of a df with the same sizes that, sometimes, are written in the wrong upper/lower cases.

Size
______

YT TRUEVIEW
YT PRE-ROLL
YT TRUEVIEW something

I want to check in the list if the lower/upper cases are correct. If not, I want to substitute with the right one. The match must be exact (not considering the upper/lower cases). My expected output is:

Size
______

YT trueview
YT pre-roll
YT TRUEVIEW something

How can i do it in pandas?

Upvotes: 1

Views: 35

Answers (1)

Shubham Sharma
Shubham Sharma

Reputation: 71687

Let's create a mapping dictionary which maps the lower case strings to their corresponding representation in list_size, then use .str.lower + .replace on column Size to substitute the matching representation from mapping dict:

dct = dict(zip(map(str.lower, list_sizes), list_sizes))
df['Size'] = df['Size'].str.lower().replace(dct)

                    Size
0            YT trueview
1            YT pre-roll
2  YT TRUEVIEW something

Upvotes: 1

Related Questions