Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Apply Function That returns two new columns

I have a pandas dataframe that I would like to use an apply function on to generate two new columns based on the existing data. I am getting this error: ValueError: Wrong number of items passed 2, placement implies 1

import pandas as pd
import numpy as np

def myfunc1(row):
    C = row['A'] + 10
    D = row['A'] + 50
    return [C, D]

df = pd.DataFrame(np.random.randint(0,10,size=(2, 2)), columns=list('AB'))

df['C', 'D'] = df.apply(myfunc1 ,axis=1)

Starting DF:

   A  B
0  6  1
1  8  4

Desired DF:

   A  B  C   D
0  6  1  16  56
1  8  4  18  58
like image 830
user2242044 Avatar asked Dec 25 '17 15:12

user2242044


People also ask

How do I return two columns in Pandas DataFrame?

Return multiple columns using Pandas apply() method Objects passed to the pandas. apply() are Series objects whose index is either the DataFrame's index (axis=0) or the DataFrame's columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function.

How do I make two columns in one column in Pandas?

We can use Pandas' str. split function to split the column of interest. Here we want to split the column “Name” and we can select the column using chain operation and split the column with expand=True option.


1 Answers

Based on your latest error, you can avoid the error by returning the new columns as a Series

def myfunc1(row):
    C = row['A'] + 10
    D = row['A'] + 50
    return pd.Series([C, D])

df[['C', 'D']] = df.apply(myfunc1 ,axis=1)
like image 78
oim Avatar answered Oct 17 '22 10:10

oim