0

I have for example 2 columns in my Dataframe

    A    B
0   4   True
1   3   False
2   4   False
3   3   True

And I now want to add 1 to the value in A if B is True and subtract 2 if B is False.

Is there a clean way to put this in an if without looping through all rows? What I really want to do is a bit more complicated than subtracting and adding but I simplified it here for the question. So I am happy about not super short answers specified to adding 1 and subtracting 2.

Hope someone can help me :)

Pasgru
  • 25
  • 7

1 Answers1

1

You can use np.where in which you use column "B" as the condition:

df['A'] = np.where(df['B'], df['A'].add(1), df['A'].sub(2))

Output:

   A      B
0  5   True
1  1  False
2  2  False
3  4   True
  • I appreciate the fast response, but this only does half of what I need plus I dont need it to add 1 in my real code. I just need a way to do something to A if B is True and something else if B is negative. I actually check if the time that is stored in A is correct. If B is True the time is fine, if its False I have to add +1 day to it as the day changed from 23:59 to 00:00 Thats what I actually need to do but I figured that it would only complicate things if I tried to explain that. – Pasgru Feb 02 '22 at 00:47
  • @Pasgru it's the same concept, use `df["B"]` as the condition and use `np.where` to assign values to "A". Just replace `df['A'].add(1)` with `"df['A']"`, and `df['A'].sub(2)` with `"add +1 day"` –  Feb 02 '22 at 00:49
  • 1
    And although I have been here for over 5 years I still can't upvote yet because not enough reputation :') but yes accepted your answere – Pasgru Feb 02 '22 at 01:02
  • 1
    There we go. You should have enough rep now @Pasgru :) –  Feb 02 '22 at 01:05
  • FYI: a possibly more readable version of @enke's answer would be `df['A'] = np.where(df['B'], df['A'] + 1, df['A'] - 2)` –  Feb 02 '22 at 01:06
  • Thanks here the code I used that maybe explains a bit why I rephrased the question: `df[column] = np.where(df["time_ok"], pd.to_datetime(df["CREATION DATE"] + ' ' + df[column], format='%d.%m.%Y %H:%M:%S'), pd.to_datetime(df["CREATION DATE"] + ' ' + df[column], format='%d.%m.%Y %H:%M:%S') + datetime.timedelta(days=1))` – Pasgru Feb 02 '22 at 01:13
  • @Pasgru perhaps it's more efficient to write it in two lines: `df[column] = pd.to_datetime(df["CREATION DATE"] + ' ' + df[column], format='%d.%m.%Y %H:%M:%S'); df[column] = np.where(df["time_ok"], df[column], df[column] + datetime.timedelta(days=1))` –  Feb 02 '22 at 03:09