2

I've searched quite a bit for a solution, but almost all questions are related to the creation of a single column. So, here is my problem.

Given an example DataFrame:

df = pd.DataFrame({
    "blue": [5, 5, 4], 
    "red": [1, 7, 5],
    "yellow": [3, 9, 0],
    "orange": [9, 7, 3],
    "config": ["north", "south", "north"]
})
   blue config  orange  red  yellow
0     5  north       9    1       3
1     5  south       7    7       9
2     4  north       3    5       0

What I would like to achieve is to create additional columns based on multiple conditions (a mapping to be specific). Here is an example of what I have tried:

def gen_col(row):

    if row["config"] == "north":
        new_blue = row["blue"]
        new_red = row["red"]
        new_yellow = row["yellow"]
        new_orange = row["orange"]
        return new_blue, new_red, new_yellow, new_orange
    elif row["config"] == "south":
        new_blue = row["orange"]
        new_red = row["yellow"]
        new_yellow = row["red"]
        new_orange = row["blue"]
        return new_blue, new_red, new_yellow, new_orange

df["new_blue", "new_red", "new_yellow", "new_orange"] = df.apply(gen_col, axis=1)

However, this returns the following:

   blue config  orange  red  yellow (new_blue, new_red, new_yellow, new_orange)
0     5  north       9    1       3             (5, 1, 3, 9)
1     5  south       7    7       9             (7, 9, 7, 5)
2     4  north       3    5       0             (4, 5, 0, 3)                         

Any ideas on how to create separate new columns?

1 Answer 1

4

Use result_type='expand' parameter in DataFrame.apply and also add nested lists for assigned columns:

df[["new_blue", "new_red", "new_yellow", "new_orange"]] = df.apply(gen_col, axis=1, result_type='expand')
print (df)
   blue  red  yellow  orange config  new_blue  new_red  new_yellow  new_orange
0     5    1       3       9  north         5        1           3           9
1     5    7       9       7  south         7        9           7           5
2     4    5       0       3  north         4        5           0           3
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the lightning fast reply! And note to self, take a (closer) look at the docs :)
@jezrael You seem to be very knowledgeable in pandas. Could you please help me by providing your views on this? stackoverflow.com/questions/62069465/… Thanks.

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.