0

For example I have the following DataFrame:

A header header. 1 header. 2 header. 3
First 111 121 323
Second 222 212 232

I want my new column to be based on the following if condition: if (value in df.header1 > than 0, then add 2) and (value in df.header2 is between 2 and 3, then add 5) and (value in df.header3 and < 400, then add 11)

so my new df would look like this:

A header header. 1 header. 2 header. 3 condition_head
First 111 121 323 13
Second 222 212 232 12
1
  • What's going on with 12 in df['condition_head']? Commented Nov 1, 2021 at 20:47

3 Answers 3

2

Based on your logic use:

df['output'] = (df['header.1'].gt(0) * 2 +
                df['header.2'].between(2,3) * 5 +
                df['header.3'].lt(400) * 11 )

Output:

  A header  header. 1  header. 2  header. 3  output
0    First        111        121        323      13
1   Second        222        212        232      13

I'm not sure how you get to your expected output.

Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted of the 3. I forgot about the built-in methods
1
df['condition_head'] = 0
df['condition_head'] += 2 * (df['header.1'] > 0)
df['condition_head'] += 5 * (df['header.2'] > 2 and df['header.2'] < 3)
df['condition_head'] += 11 * (df['header.3'] > 400)

Comments

0

Try using df.apply() and a self defined helper function:

def helper(x):
    ans= 0
    if 0< x['header.1']:
        ans+=2
    if 2< x['header.2']<=3:
        ans+=5
    if x['header.3']<400:
        ans+=11
    return ans
df['contition_head'] = df.apply(helper, axis=1)

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.