-1

Please read before pointing me to this thread: Python Pandas replace values by their opposite sign

I have the following DataFrame:

A      | B
"1.9"  | "S"
"1.2"  | "H"
"1.9"  | "S"

I want to replace values in column A to the values with opposite sign for all rows where B is "S", so the outcome is as follows:

A       | B
"-1.9"  | "S"
"1.2"   | "H"
"-1.9"  | "S"

Unfortunately all values are String.

I don't have a problem with setting the right query and update matching values with something else:

data.loc[(data["B"]) == 'S', data.columns[1]] = 999

This will result with the following:

A       | B
"999"   | "S"
"1.2"   | "H"
"999"   | "S"

So I know how to the the right entries for updates, but I have no idea how to update the values with their opposite sign.

0x4ndy
  • 1,216
  • 1
  • 12
  • 25
  • 2
    What does "Unfortunately all values are String." mean? Do you know that this is not helpful and want to say that you have to stick with it? Or don't you know how to cast those strings to float, multiply by -1 and (if really needed) cast back to string? Or is that not allowed? – SpghttCd Jul 19 '19 at 19:37
  • 1
    Your problem can be solved but your question will most certainly not be useful because nearly everyone else will represent their data more sensibly. – cs95 Jul 19 '19 at 19:38
  • If they are numbers and you want to treat them as numbers, why not keep them as numbers? – harvpan Jul 19 '19 at 19:42
  • @SpghttCd I did ask a very specific question providing as much details as possible. Thanks for the answer. – 0x4ndy Jul 19 '19 at 19:56
  • @cs95 they are string and I want them to be string. The problem is just as I described (and is already answered). – 0x4ndy Jul 19 '19 at 19:57
  • Problem is a lot of people don't know what they want. Take a look at the [XY problem.](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) Unfortunately without further context, there's nothing more I can say about your problem, except that you will almost never ever want to represent strings as '"xyz"' (with the extra enclosing double quotes) as your data seems to indicate. – cs95 Jul 19 '19 at 20:45

2 Answers2

3

Check np.where

df['A']=np.where(df['B']=='S', '-'+df['A'], df['A'])

As recommended by SpghttCd

df['A']=np.where((df['B']=='S')&(~df.a.str.startswith('-')), '-'+df['A'], df['A'])
BENY
  • 317,841
  • 20
  • 164
  • 234
  • 2
    @SpghttCd, you are right. `np.where(df['B']=='S', df['A'].astype(float).mul(-1).astype(str), df['A'])` should do. – harvpan Jul 19 '19 at 19:41
2

Still using pandas .loc

 df.loc[df.B =='S', 'A'] = (df.A.astype(float)*-1).astype(str)

I'm assuming that both input and output are meant to be string values

Connor John
  • 433
  • 2
  • 8