从 DataFrame.apply 创建数据帧

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

我有一个函数,给定另一个数据帧的一行,返回

pd.DataFrame

def func(row):
    if row['col1']== 1:
        return pd.DataFrame({'a':[1], 'b':[11]})
    else:
        return pd.DataFrame({'a':[-1, -2], 'b':[-11,-22]})

我想使用 apply

func
到另一个数据框来创建一个新的数据框,如下所示:

df = pd.DataFrame({'col1':[1,2,3],'col2':[11,22,33]})

# do some cool pd.DataFrame.apply stuff
# resulting in the below dataframe
pd.DataFrame({
    'a':[1,-1,-2,-1,-2],
    'b':[11,-11,-22,-11,-22]
})

目前,我使用下面的代码来获得所需的结果:

pd.concat([mini[1] for mini in df.apply(func,axis=1).iteritems()])

虽然这有效,但相当难看。有没有更优雅的方法来从

df
创建数据框?

python-3.x pandas pandas-apply
1个回答
1
投票

您可以使用:

pd.concat(df.apply(func, axis=1).tolist())

输出:

   a   b
0  1  11
0 -1 -11
1 -2 -22
0 -1 -11
1 -2 -22
© www.soinside.com 2019 - 2024. All rights reserved.