0
$\begingroup$

In Stata, I can perform a conditional replace using the following code:

replace target_var = new_value if condition_var1 == x & condition_var2 == y

What's the most pythonic way to reproduce the above on a pandas dataframe? Bonus points if I can throw the new values, and conditions into a dictionary to loop over.

To add a bit more context, I'm trying to clean some geographic data, so I'll have a lot of lines like

replace county_name = new_name_1 if district == X_1 and city == Y_1
....
replace county_name = new_name_N if district == X_N and city == Y_N

What I've found so far:

  1. pd.replace which lets me do stuff like the following, but doesn't seem to accept logical conditions:

`

replacements = {   1: 'Male',   2: 'Female',   0: 'Not Recorded' }

df['sex'].replace(replacements, inplace=True)

`

$\endgroup$
1
  • $\begingroup$ search for masking using np.where or loc,iloc,idx... $\endgroup$
    – Aditya
    Commented Jun 5, 2018 at 6:43

2 Answers 2

1
$\begingroup$

df.where(condition, replacement, inplace=True)

Condition is assumed to be boolean Series/Numpy array. Check out where documentation - here is an example.

$\endgroup$
0
$\begingroup$

Maybe you can use the nested dictionary combined with a simple Pandas condition to do this. To show you what I mean, let's take a look at the following example:

test = [ {'Account': 'Jones', 'City': 'Paris'},
         {'Account': 'Alpha',  'City': 'Rome'} ,
         {'Account': 'Jack',  'City': 'Paris'},
         {'Account': 'Rose',  'City': 'Berlin'},
         {'Account': 'Cassandra',  'City': 'London'}]

df = pd.DataFrame(test)
df
    Account City
0   Jones   Paris
1   Alpha   Rome
2   Jack    Paris
3   Rose    Berlin
4   Cassandra   London

Let's say you want to replace the the City Paris to Barcelona only if Account name is Jones (co. You can achieve this easily in two steps:

1) Construct your desired replacement dictionary for the City (one condition):

condition={'City': {'Paris': 'Barcelona'}}

2) Filter down your pandas column where you want the change (second condition)

df[df['Account']=='Jones'].replace(condition)

Which you yield you:

    Account City
0   Jones   Barcelona

I can imagine there will many different ways this can be done, but for I thought of this. ;-)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.