简体   繁体   中英

Writing the output of df.apply() to multiple columns at once

I am trying to write the results of a function that returns multiple arguments to multiple Pandas columns.

Originally, I used zip(*df.apply(..) ), but this feel very 'hacky' and unPythonic.

I have found that df.apply() has an argument result_type='expand', which seemed to do what I was looking for: return multiple columns.

However, when expanding this result to columns I receive very strange results (see code).

df['A'] = range(4)

def square(row):
    return row['A']**2, row['A']**3
df.apply(square, axis=1, result_type='expand')
>>>
    0   1
0   0   0
1   1   1
2   4   8
3   9   27
df['B'], df['C'] = df.apply(square, axis=1, result_type='expand')
df
>>>
    A   B   C
0   0   0   1
1   1   0   1
2   2   0   1
3   3   0   1

I expected DF['B'] and DF['C'] to contain the returned columns 0 and 1 with correct values, but they contain series of 0 and series of 1.

What is the correct and Pythonic way to write the result of an apply function to multiple DataFrame columns?

Try assigning the expand while creating 2 new columns like:

df[['B','C']]=df.apply(square, axis=1, result_type='expand')
print(df)

   A  B   C
0  0  0   0
1  1  1   1
2  2  4   8
3  3  9  27

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM