将pandas数据框与apply(lambda)的结果连接起来,其中lambda返回另一个数据框 [英] Concatenate pandas dataframe with result of apply(lambda) where lambda returns another dataframe

查看:146
本文介绍了将pandas数据框与apply(lambda)的结果连接起来,其中lambda返回另一个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个数据框在列中存储一些值,并将这些值传递给我得到另一个数据框的函数。我想将返回的数据框的列连接到原始数据框。

A dataframe stores some values in columns, passing those values to a function I get another dataframe. I'd like to concatenate the returned dataframe's columns to the original dataframe.

我试图做类似的事情

i = pd.concat([i, i[['cid', 'id']].apply(lambda x: xy(*x), axis=1)], axis=1) 

但它没有错误:

ValueError: cannot copy sequence with size 2 to array axis with dimension 1

所以我这样做了:

def xy(x, y):
    return pd.DataFrame({'x': [x*2], 'y': [y*2]})

df1 = pd.DataFrame({'cid': [4, 4], 'id': [6, 10]})
print('df1:\n{}'.format(df1))


df2 = pd.DataFrame()
for _, row in df1.iterrows():
    nr = xy(row['cid'], row['id'])
    nr['cid'] = row['cid']
    nr['id'] = row['id']
    df2 = df2.append(nr, ignore_index=True)

print('df2:\n{}'.format(df2))

输出:

df1:
   cid  id
0    4   6
1    4  10

df2:
   x   y  cid  id
0  8  12    4   6
1  8  20    4  10

代码看起来不太好,应该运行缓慢。

The code does not look nice and should work slowly.

是否有熊猫/ pythonic方式来正确且快速地工作?

Is there pandas/pythonic way to do it properly and fast working?

python 2.7

python 2.7

推荐答案

选项0

最直接使用 pd.DataFrame.assign 。不是很通用。

df1.assign(x=df1.cid * 2, y=df1.id * 2)

   cid  id  x   y
0    4   6  8  12
1    4  10  8  20

选项1

使用 pd.DataFrame.join 添加新列

这显示如何在将 apply lambda

df1.join(df1.apply(lambda x: pd.Series(x.values * 2, ['x', 'y']), 1))

   cid  id  x   y
0    4   6  8  12
1    4  10  8  20






选项2

使用 pd.DataFrame.assign 添加新列
这显示在将 apply lambda

df1.assign(**df1.apply(lambda x: pd.Series(x.values * 2, ['x', 'y']), 1))

   cid  id  x   y
0    4   6  8  12
1    4  10  8  20






选项3

但是,如果您的函数确实只是乘以 2

df1.join(df1.mul(2).rename(columns=dict(cid='x', id='y')))

Or

df1.assign(**df1.mul(2).rename(columns=dict(cid='x', id='y')))

这篇关于将pandas数据框与apply(lambda)的结果连接起来,其中lambda返回另一个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆