使用 df.apply() 返回多个值

问题描述 投票:0回答:1

在下面的程序中,我想在调用

df.apply(custom_function)
时将消息作为单独的变量返回。 可以这样做吗

import pandas as pd

data = {'Column1': [1, 2, 3, 4, 5], 'Column2': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)

def custom_function(row):
    message = "Done"
    return row['Column1'] + row['Column2']


df['Result'] = df.apply(custom_function, axis=1)

print(df)

[df['Result'] = df.apply(custom_function, axis=1), message] = df.apply(custom_function, axis=1)
不起作用,
df['Result'] = df.apply(custom_function, axis=1)
return row['Column1'] + row['Column2'], message
会向每一行添加消息。

python pandas
1个回答
0
投票

你可以这样做:

import pandas as pd

data = {'Column1': [1, 2, 3, 4, 5], 'Column2': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)

def custom_function(row):
    message = "Done"
    return row['Column1'] + row['Column2'], message

df[['Result', 'Status']] = df.apply(custom_function, axis=1, result_type='expand')
df


   Column1  Column2  Result Status
0        1       10      11   Done
1        2       20      22   Done
2        3       30      33   Done
3        4       40      44   Done
4        5       50      55   Done
© www.soinside.com 2019 - 2024. All rights reserved.