Python Pandas how to update a column if another column contains a certain string

Viewed 2391

I have a dataframe and I want to replace the value in MinP with the value in MaxP ONLY if MaxP has a +/- [I will then remove the +/- and convert to a number]

My code kind of works but it puts a 0 in MinP when Maxp does not have a +/- instead I want to keep the value, if any, of MinP

import pandas as pd 
df = pd.DataFrame({
    'MinP':['0','','-10','',],
    'MaxP':['20','15','12','+/-20']})

print(df)

df['MinP'] = df['MaxP'].apply(lambda x: df['MaxP'] if '+/-' in x else df['MinP'])
print(df)

    MinP   MaxP
0    0     20
1          15
2  -10     12
3       +/-20
    MinP   MaxP
0    0     20
1    0     15
2    0     12
3   20  +/-20

I also played around with: df.loc[df['MinP']] = np.where(df.MaxP.str.contains("+/-"), df['MaxP'],df.MinP) but didn't get anywhere.

Any other ideas?

2 Answers

+ is a special char in regex, so you need to do contains('\+/-'). Also, fillna is handy:

df['MinP'] = df.MaxP.str.extract('^\+/-(\d+)')[0].fillna(df.MinP)

Output:

 MinP   MaxP
0    0     20
1          15
2  -10     12
3   20  +/-20

Note: '^\+/-(\d+)' only extract the digits. If your data contains other characters, e.g. 20.1 or 2e10, you can use '^\+/-(.+)'

You could use str.contains + numpy.where:

df['MinP'] = np.where(df.MaxP.str.contains('+/-', regex=False), df.MaxP, df.MinP)
print(df)

Output

    MinP   MaxP
0      0     20
1            15
2    -10     12
3  +/-20  +/-20

Notice that you must use regex=False to avoid the pattern being interpreted as a regular expression.

Related