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.
df['new_column'] = df.apply(lambda x: x.str.contains("REPLACE").sum(), axis=1)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.