如何将数据帧合并到另一个由pandas python中第一个数据帧的产品创建的数据帧中?

2024-03-29 09:10:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列为a,B的数据帧,然后函数foo(B)从第一个返回基于B值的行数的数据帧中获取参数B

import pandas as pd
import numpy as np
x = pd.DataFrame.from_items([('A', [1,1, 2, 3]), ('B', [4,3, 5, 6])])
def foo(B):
    sX = pd.Series(np.random.randn(B))
    sY = pd.Series(np.random.randn(B))
    return pd.DataFrame.from_items([('X', sX.tolist()), ('Y', sY.tolist())])
foo(4)
foo(3)

我最终想创建一个合并两个表的新数据帧。在

enter image description here ;;;;;; enter image description here

我希望我的输出如下所示。。。 enter image description here


Tags: 数据fromimportdataframefooasnpitems
2条回答
x = pd.DataFrame.from_items([('A', [1,1, 2, 3]), ('B', [4,3, 5, 6])])

def foo(B):
    df = pd.DataFrame(np.random.randn(B,2), columns=['X','Y'])
    df['tmp'] = B
    return df

x.merge(pd.concat([foo(4), foo(3)]), left_on='B', right_on='tmp', how='left').drop('tmp',1)

按列AB对数据帧x分组,然后使用apply方法为每个组生成数据帧:

(x.groupby(['A', 'B']).apply(lambda g: foo(g.B))
  .reset_index(level=2, drop=True).reset_index())

enter image description here

相关问题 更多 >