add multiple columns to pandas dataframe

A Hansson

The following Python code works fine

import pandas as pd

df = pd.DataFrame(data = {'a': [1, 2, 3], 'b': [4, 5, 6]})

def myfun(a, b):
  return [a + b, a - b]

df[['x', 'y']] = df.apply(
    lambda row: myfun(row.a, row.b), axis=1)

The resulting pandas dataframe looks like:

print(df)

   a  b  x  y
0  1  4  5 -3
1  2  5  7 -3
2  3  6  9 -3

However, if I try to add two more columns,

df[['xx','yy']] = df.apply(lambda row: myfun(row.a, row.b), axis=1)

I get the error message,

KeyError: "['xx' 'yy'] not in index"

How come? And what is the correct way to do this?

Many thanks!

//A

jezrael

Need convert return output to Series:

def myfun(a, b):
  return pd.Series([a + b, a - b])

df[['x', 'y']] = df.apply(
    lambda row: myfun(row.a, row.b), axis=1)
print (df)
   a  b  x  y
0  1  4  5 -3
1  2  5  7 -3
2  3  6  9 -3

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Python pandas add multiple columns to dataframe with map

Add multiple empty columns to pandas DataFrame

Add Multiple Columns to Pandas Dataframe from Function

Add multiple columns and values to a pandas dataframe

Add multiple columns to a Pandas dataframe quickly

Pandas - how to add multiple conditional columns to dataframe?

Add a column to Pandas DataFrame with multiple lookups based on other columns

How to add multiple columns to pandas dataframe in one assignment?

How can I add multiple variable arrays to columns in a pandas dataframe?

Pandas: Read a text file and add values to multiple columns in a dataframe

Add columns in pandas dataframe dynamically

Add more columns to a Pandas Dataframe

How to add multiple columns to a DataFrame?

Add quantiles to dataframe as multiple columns

transpose multiple columns Pandas dataframe

Reshape pandas dataframe for multiple columns

compare multiple columns in a pandas dataframe

Pandas dataframe group by multiple columns

transpose multiple columns in a pandas dataframe

Pivot a pandas dataframe with multiple columns

Selecting multiple columns in a pandas dataframe

Selecting multiple columns in a pandas dataframe

Pandas Dataframe Groupby multiple columns

Formatting multiple columns in dataframe pandas

Transposing a pandas dataframe with multiple columns

reshape a pandas dataframe with multiple columns

Pandas dataframe to excel into multiple columns

Exploding pandas dataframe on multiple columns

Pandas dataframe add integer columns into datetime columns