0

I have just started to learn python and don't have much of dev background. Here is the code I have written while learning.

I now want to make a function which exactly does what my "for" loop is doing but it needs to calculate different exp(exp,exp1 etc) based on different num(num, num1 etc)

how can I do this?

import pandas as pd
index = [0,1]
s = pd.Series(['a','b'],index= index)
t = pd.Series([1,2],index= index)
t1 = pd.Series([3,4],index= index)
df = pd.DataFrame(s,columns = ["str"])
df["num"] =t
df['num1']=t1

print (df)

exp=[]

for index, row in df.iterrows():
    if(row['str'] == 'a'):
        row['mul'] = -1 * row['num'] 
        exp.append(row['mul'])
    else:
        row['mul'] = 1 * row['num'] 
        exp.append(row['mul'])
df['exp'] = exp

print (df)

This is what i was trying to do which gives wrong results

import pandas as pd
index = [0,1]
s = pd.Series(['a','b'],index= index)
t = pd.Series([1,2],index= index)
t1 = pd.Series([3,4],index= index)
df = pd.DataFrame(s,columns = ["str"])
df["num"] =t
df['num1']=t1

def f(x):
    exp=[]

    for index, row in df.iterrows():
        if(row['str'] == 'a'):
            row['mul'] = -1 * x
            exp.append(row['mul'])
        else:
            row['mul'] = 1 * x 
            exp.append(row['mul'])
    return exp

df['exp'] = df['num'].apply(f)
df['exp1'] = df['num1'].apply(f)
df

Per suggestion below, I would do:

df['exp']=np.where(df.str=='a',df['num']*-1,df['num']*1)
df['exp1']=np.where(df.str=='a',df['num1']*-1,df['num1']*1)

2 Answers 2

1

I think you are looking for np.where

df['exp']=np.where(df.str=='a',df['num']*-1,df['num']*1)
df
Out[281]: 
  str  num  num1  exp
0   a    1     3   -1
1   b    2     4    2
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I can see how np.where does same thing efficiently what for/if/else was doing. What i actually want to do is make this a function which can accept different values for num and generate different exp. So, in this example, num, num1 should be input to function and result should add exp, exp1 to df
I updated the question. I was trying to use function but i think do the same with your suggestion
0

Normal dataframe operation:

df["exp"] = df.apply(lambda x: x["num"] * (1 if x["str"]=="a" else -1), axis=1)

Mathematical dataframe operation:

df["exp"] = ((df["str"] == 'a')-0.5) * 2 * df["num"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.