2

I imported a Dataframe using pandas then wrote some code (as below) to create an additional column. I need to extract a subset of the newly added column and then create an if statement that will allow me to look at the last 2 values of the integers and apply the following logic:

  • If the integer ends in 9 perform a +2 addition (for example: 9+2=11)
  • For anything else perform a +1 addition (for example 4+1=5)

This is the code I've written so far to create the additional column:

max_items['ind_short'] = ((max_items['Item'] % 1000).astype(int))

Can anyone help?

Community
  • 1
  • 1
  • 3
    Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful. – jezrael Sep 04 '18 at 10:49
  • 2
    provide sample data with expected outcome – Sociopath Sep 04 '18 at 10:49
  • What format is your data? – Josh Friedlander Sep 04 '18 at 11:02

1 Answers1

2

Assuming by last number within the column you mean the units value of an integer, you can use the modulo operator %. Then use numpy.where to perform your mapping:

df = pd.DataFrame({'A': [6357, 1325, 549, 12312, 19]})

df['B'] = np.where(df['A'] % 10 == 9, 2, 1)

print(df)

       A  B
0   6357  1
1   1325  1
2    549  2
3  12312  1
4     19  2
jpp
  • 159,742
  • 34
  • 281
  • 339