小编Ror*_*itt的帖子

Python/pandas - 使用 DataFrame.apply 和返回字典的函数

我知道如何在数据帧上使用 apply 函数来计算新列并将它们附加到数据帧。我的问题是,如果我有一个函数,它接受多个值(对应于当前数据框中的列)并返回一个字典(对应于我想要添加到数据框中的列)作为参数,是否有一种简单/优雅的方法将此函数应用于数据框并生成新列?

例如,目前我正在这样做:

import pandas as pd
import numpy as np

col1 = [np.random.randn()] * 10
col2 = [np.random.randn()] * 10
col3 = [np.random.randn()] * 10

df = pd.DataFrame({'col1': col1,
                   'col2': col2,
                   'col3': col3 })

df['col4'] = df.apply(lambda x: get_col4(x['col1'], x['col2']), axis=1)
df['col5'] = df.apply(lambda x: get_col5(x['col1'], x['col2'], x['col3']), 
axis=1)
df['col6'] = df.apply(lambda x: get_col6(x['col3'], x['col4'], x['col5']), 
axis=1)
df['col7'] = df.apply(lambda x: get_col7(x['col4'], x['col6']), axis=1)
Run Code Online (Sandbox Code Playgroud)

其中每个计算列都有单独的函数,每个函数都依赖于前面列的某种组合。

但是,由于计算列的值是相互依赖的,因此我认为使用如下所示的函数一次计算所有新列会更加高效和优雅:

def get_cols(col1, col2, col3):
    #some calculations...
    return {'col4': col4,
            'col5': col5,
            'col6': …
Run Code Online (Sandbox Code Playgroud)

python pandas

9
推荐指数
2
解决办法
1万
查看次数

标签 统计

pandas ×1

python ×1