pandas overwrite values in multiple columns at once based on condition of values in one column
You need series.str.len()
after splitting to determining the length of the list , then you can compare and using .loc[]
, assign the the list wherever condition matches:
df.loc[df['col1'].str.split(":").str.len()>2,['col1','col2','col3']]=["", "", False]
print(df)
col0 col1 col2 col3 col4
0 11 False elo
1 22 a:a foo False foo
2 1 a foobar True bar
3 5 False dupa
Use Series.str.count
, add 1
, compare by Series.gt
and assign list to filtered columns in list:
df.loc[df['col1'].str.count(":").add(1).gt(2), ['col1','col2','col3']] = ["", "", False]
print (df)
col0 col1 col2 col3 col4
0 11 False elo
1 22 a:a foo False foo
2 1 a foobar True bar
3 5 False dupa
Another approach is Series.str.split
with expand = True
and DataFrame.count
with axis=1
.
df.loc[df['col1'].str.split(":",expand = True).count(axis=1).gt(2),['col1','col2','col3']]=["", "", False]
print(df)
col0 col1 col2 col3 col4
0 11 False elo
1 22 a:a foo False foo
2 1 a foobar True bar
3 5 False dupa