My data-frame consists of StoreId which needs to be changed for a particular type of store:
StoreType StoreId
A 105
A 213
B 401
B 402
B 711
B 910
B 913
B 915
In this dataframe, just for storeType = B, I want to get rid of all the 4's if the storeId starts with 4,(for example, 401 should change to 01, 402 should change to 02), for any other StoreID with storetype = B, there is no such logic and hence it needs to be hard coded like 711 should change to I0, 910 to 801, 913 to 804, 915 to 814.
How can I write an efficient code using pandas data-frame in python??
You can use a simple regular expression here, along with where
to only change columns where a B
is found in the other series.
u = df.StoreId.astype(str)
df.assign(StoreId=u.where(df.StoreType.ne('B'), u.str.replace('^4', '')))
StoreType StoreId
0 A 105
1 A 213
2 B 01
3 B 02
4 B 711
5 B 910
6 B 913
7 B 915
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments