Reputation: 637
I have a python program which process multiple files. Each file have customer id column based on value in city column. Some file has 8 digit customer id and some have 9 digit customer id. I need to do this -
if column city value is in ['Chicago', 'Newyork', 'Milwaukee', 'Dallas']:
input_file['customer_id'] = input_file['customer_id'].str[0:2] + '-' + input_file['customer_id'].str[2:8]
Else:
input_file['customer_id'] = 'K' + '-' + input_file['customer_id'].str[0:3] + '-' + input_file['customer_id'].str[3:8]
Input
id cusotmerid city
1 89898988 Dallas
2 898989889 Houston
Output
id cusotmerid city
1 89-898988 Dallas
2 K-898-989889 Houston
How can I achieve it.
Upvotes: 0
Views: 35
Reputation: 323226
Check with np.where
l = ['Chicago', 'Newyork', 'Milwaukee', 'Dallas']
s1 = df['customer_id'].str[0:2] + '-' + df['customer_id'].str[2:8]
s2 = 'K' + '-' + df['customer_id'].str[0:3] + '-' + df['customer_id'].str[3:8]
df['cusotmerid'] = np.where(df['city'].isin(l), s1, s2)
Upvotes: 1