I have a dataframe with mixed data types and I would like to change the values of str cells (each consisting of two letters plus three numbers) so that uneven number become even numbers but the number decreases. AB123 should become AB122 while not changing the letter before it.
Here is an example dataframe with mixed types:
df = pd.DataFrame({'Opportunity':['AB122','AB123','AB125', 'AB124'],
'Quantity': [2, 3, 4, 1],
'Member': ["AACC", "AACC", "AACC", 'DDEE']})
print (df)
Opportunity Quantity Member
0 AB122 2 AACC
1 AB123 3 AACC
2 AB121 4 AACC
3 AB120 1 DDEE
I would like the outcome to be:
print (df2)
Opportunity Quantity Member
0 AB122 2 AACC
1 AB122 3 AACC
2 AB120 4 AACC
3 AB120 1 DDEE
Try:
df['Opportunity'] = df['Opportunity'].str[:2] + np.where(df['Opportunity'].str[2:].astype(int) % 2, df['Opportunity'].str[2:].astype(int).sub(1).astype(str), df['Opportunity'].str[2:])
And now:
print(df)
Is:
Member Opportunity Quantity
0 AACC AB122 2
1 AACC AB122 3
2 AACC AB120 4
3 DDEE AB120 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With