Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of uneven to specific even numbers

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
like image 612
MHanu Avatar asked Jul 11 '19 08:07

MHanu


1 Answers

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
like image 152
U12-Forward Avatar answered Sep 19 '22 20:09

U12-Forward