Reputation: 105
Lets say I have a dataframe that looks like this:
Select a BW Speed Router Name router_max OK or REPLACE? Firewall Name firewall_max OK or REPLACE?
0 50 XYZ 30.0 REPLACE X 30.0 REPLACE
1 50 XYZ 30.0 REPLACE X NaN N/A
2 50 XYZ 30.0 REPLACE X 30.0 REPLACE
I need an additional column that shows the number of times "REPLACE" occurs in that row (in this case it is the total number of items that need to be replaced).
Any help would be appreciated...I know this is probably pretty basic stuff.
Upvotes: 2
Views: 2256
Reputation: 23099
using stack
and groupby
with str_contains
to avoid using apply.
df["replace_check"] = (
df.stack().to_frame()[0].str.contains("REPLACE").groupby(level=0).sum()
)
print(df)
Select a BW Speed Router Name router_max OK or REPLACE? \
0 50 XYZ 30.0 REPLACE
1 50 XYZ 30.0 REPLACE
2 50 XYZ 30.0 REPLACE
Firewall Name firewall_max OK or REPLACE? replace_check
0 X 30.0 REPLACE 2.0
1 X NaN N/A 1.0
2 X 30.0 REPLACE 2.0
Upvotes: 0
Reputation: 467
df['new_column'] = df.apply(lambda x: x.str.contains("REPLACE").sum(), axis=1)
Upvotes: 2