-3

I have a pandas Dataframe and Series of the form

df = pd.DataFrame({'Key':[2345,2542,5436,2468,7463],
                   'Segment':[0] * 5,
                   'Values':[2,4,6,6,4]})
print (df)
    Key  Segment  Values
0  2345        0       2
1  2542        0       4
2  5436        0       6
3  2468        0       6
4  7463        0       4

s = pd.Series([5436, 2345])
print (s)
0    5436
1    2345
dtype: int64

In the original df, I want to multiply the 3rd column(Values) by 7 except for the keys which are present in the series. So my final df should look like

enter image description here

What should be the best way to achieve this in Python 3.x?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
vicky113
  • 351
  • 1
  • 6
  • 19
  • [Please don't post images of code/data (or links to them)](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question) – jezrael Mar 31 '19 at 16:33
  • Have a look at `https://stackoverflow.com/questions/19960077/how-to-implement-in-and-not-in-for-pandas-dataframe also please do not paste images of data/code – anky Mar 31 '19 at 16:33

2 Answers2

3

Use DataFrame.loc with Series.isin for filter Value column with inverted condition for non membership with multiple by scalar:

df.loc[~df['Key'].isin(s), 'Values'] *= 7
print (df)
    Key  Segment  Values
0  2345        0       2
1  2542        0      28
2  5436        0       6
3  2468        0      42
4  7463        0      28
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

Another method could be using numpy.where():

df['Values'] *= np.where(~df['Key'].isin([5436, 2345]), 7,1)
Loochie
  • 2,414
  • 13
  • 20