Mason J.
Mason J.

Reputation: 65

Multiple If-else statement results

How do I set up a if statement for multiple answers rather than conditions?

So for my example, I want to say that if i equal 0, then a and b will have unique answers.

df is a dataframe something like:

0 d 8
0 d 9
0 t 7
1 q 7
0 u 8
0 r 5
1 s 3

for c in range(len(df.index)):
    for i in df.iloc[[c]],0]:
        if i == 0:
            a = 12
            b = 'up'
OUT.write('%i,%s,'%(a,b))

error is: NameError: name 'a' is not defined

I have tried:

for c in range(len(df.index)):
    for i in df.iloc[[c]],0]:
        if i == 0:
            a = 12; b = 'up'

and

for c in range(len(df.index)):
    for i in df.iloc[[c]],0]:
        if i == 0:
            a = 12 and b = 'up'

Upvotes: 0

Views: 81

Answers (2)

rpanai
rpanai

Reputation: 13437

As alternative to df.loc used by Khalil Al Hooti you might consider using np.where in the following way

df["a"] = np.where(df.variable==0, 12, df["a"])
df["b"] = np.where(df.variable==0, "up", df["a"])

On my experiments looks a faster solution.

Update

enter image description here

Upvotes: 2

Khalil Al Hooti
Khalil Al Hooti

Reputation: 4506

Lets suppose you have the following data-set in pandas

import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['variable', 'a', 'b'])
df.variable = np.random.choice(range(5), size=10)

print(df)

The output is as follows:

  variable   a   b
0   0   NaN NaN
1   4   NaN NaN
2   0   NaN NaN
3   3   NaN NaN
4   4   NaN NaN
5   0   NaN NaN
6   3   NaN NaN
7   3   NaN NaN
8   4   NaN NaN
9   0   NaN NaN

Now you can change the items in 'a' and 'b' as follows

df.loc[df.variable == 0, 'a'] = 12
df.loc[df.variable == 0, 'b'] = "up"
print(df)

the output:

    variable    a   b
0   0   12  up
1   4   NaN NaN
2   0   12  up
3   3   NaN NaN
4   4   NaN NaN
5   0   12  up
6   3   NaN NaN
7   3   NaN NaN
8   4   NaN NaN
9   0   12  up

Upvotes: 2

Related Questions