0

Current Df of:

XXXX    apples  -1000000    Bob
XXXX    oranges -1000000    Sam
AAAA    apples  -2400000    Bob
XXXX    pears   1000000 Bob
XXXX    pears   1000000 Sam
XXXX    grapes  1000000 Bob
AAAA    grapes  1000000 Bob
XXXX    apples  1200000 Bob
AAAA    apples  1900000 Sam
XXXX    grapes  -1100000    Sam

I want to multiple the qauntity in the 3rd column by -1 if the first column is equal to 'XXXX' nd the fourth column is equal to 'Bob'

I have tried using loc and filtering on the condition but can't seem to get this right

Trying_hard
  • 8,931
  • 29
  • 62
  • 85
  • Would be really helpful to provide the sample data as text and not an image. – gbeaven Jan 14 '20 at 18:34
  • 1
    Please [edit] your question to include your sample data as text, not as code. Please also include a sample of your desired output, and the code for what you've already tried, to make a [mcve] – G. Anderson Jan 14 '20 at 18:34
  • Does this answer your question? [Pandas conditional creation of a series/dataframe column](https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column) – FBruzzesi Jan 14 '20 at 18:50

2 Answers2

2

You can use np.where():

df['col_3'] = np.where((df['col_1']=='XXXX') & (df['col_4']=='Bob'), -1*df['col_3'], df['col_3'])

Yields:

  col_1    col_2    col_3 col_4
0  XXXX   apples  1000000   Bob
1  XXXX  oranges -1000000   Sam
2  AAAA   apples -2400000   Bob
3  XXXX    pears -1000000   Bob
4  XXXX    pears  1000000   Sam
5  XXXX   grapes -1000000   Bob
6  AAAA   grapes  1000000   Bob
7  XXXX   apples -1200000   Bob
8  AAAA   apples  1900000   Sam
9  XXXX   grapes -1100000   Sam
rahlf23
  • 8,869
  • 4
  • 24
  • 54
2

Doing it in-place and maintaining the pandas df syntax -

df['col_3'] = df.where((df['col_1'] == 'XXXX') & (df['col_4'] == 'Bob'))['col_3'] * -1
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
SaRa
  • 316
  • 1
  • 4