Pradyut Vatsa Pradyut Vatsa - 6 months ago 10
Python Question

Replacing cells in a dataframe column based on one or more condition

I've a dataframe from which I need to access and replace certain cell values based on conditions:

entries_and_exits = pd.DataFrame({
'ENTRIESn': [3144312, 3144335, 3144353, 3144424, 3144594,
3144808, 3144895, 3144905, 3144941, 3145094],
'EXITSn': [1088151, 0, 1088177, 1088231, 1088275,
1088317, 1088328, 1088331, 1088420, 1088753],
'Terminal': ['A', 'B','C','D','E','F','G','H','I','J']
})


What I need to do is I need to replace the value in 'Exitsn' column with 0 if they're non zero and the value in terminal column is either of 'A', 'B', or 'G'.

Any idea how to do this? I've been brainstorming for some time now using
apply()
,
applymap()
,
where()
,
replace()
but none seem to be working. While I'm able to access individual elements that needs to be changed, I'm not able to implement an efficient way in which such a condition is checked over the entire dataframe and the elements are modified.

Answer

mask the df using isin passing a list of the values of interest, this will return a boolean mask which you can use to only replace the values where the condition is met:

In [66]:
entries_and_exits.loc[entries_and_exits['Terminal'].isin(['A','B','G']), 'EXITSn'] = 0
entries_and_exits

Out[66]:
   ENTRIESn   EXITSn Terminal
0   3144312        0        A
1   3144335        0        B
2   3144353  1088177        C
3   3144424  1088231        D
4   3144594  1088275        E
5   3144808  1088317        F
6   3144895        0        G
7   3144905  1088331        H
8   3144941  1088420        I
9   3145094  1088753        J

breaking the above down:

In [70]:
entries_and_exits['Terminal'].isin(['A','B','G'])

Out[70]:
0     True
1     True
2    False
3    False
4    False
5    False
6     True
7    False
8    False
9    False
Name: Terminal, dtype: bool

In [71]:
entries_and_exits[entries_and_exits['Terminal'].isin(['A','B','G'])]

Out[71]:
   ENTRIESn  EXITSn Terminal
0   3144312       0        A
1   3144335       0        B
6   3144895       0        G
Comments