Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas update multiple columns using apply function

Tags:

python

pandas

I am updating a data frame using apply of function.

But now I need to modify multiple columns using this function,

Here is my sample code:

def update_row(row):
    listy = [1,2,3]
    return listy

dp_data_df[['A', 'P','Y']] = dp_data_df.apply(update_row, axis=1)

It is throwing the following error:

ValueError: shape mismatch: value array of shape (10,) could not be broadcast to indexing result of shape (3,10)

Thanks in advance.

like image 457
Karthikeyan KR Avatar asked Aug 06 '18 08:08

Karthikeyan KR


People also ask

How do I apply the same function to multiple columns in Python?

Pandas apply() Function to Single & Multiple Column(s) Using pandas. DataFrame. apply() method you can execute a function to a single column, all and list of multiple columns (two or more).


1 Answers

You can return pd.Series:

dp_data_df = pd.DataFrame({'A':[3,5,6,6],
                           'B':[6,7,8,9],
                           'P':[5,6,7,0],
                           'Y':[1,2,3,4]})
print (dp_data_df)
   A  B  P  Y
0  3  6  5  1
1  5  7  6  2
2  6  8  7  3
3  6  9  0  4

def update_row(row):
    listy = [1,2,3]
    return pd.Series(listy)

dp_data_df[['A', 'P','Y']] = dp_data_df.apply(update_row, axis=1)
print (dp_data_df)
   A  B  P  Y
0  1  6  2  3
1  1  7  2  3
2  1  8  2  3
3  1  9  2  3
like image 188
jezrael Avatar answered Sep 23 '22 16:09

jezrael