Python 折叠数据帧数据集中的行

Python 折叠数据帧数据集中的行,python,pandas,Python,Pandas,我是熊猫队的新手,正在尝试创建一个非规范化的平面数据集,我想知道这是否可行。我从两个数据帧开始,一个是父数据帧,另一个是子数据帧,从概念上讲,它们可以连接到一个列(“PID”) 以下是父数据帧: parentData = [(1,’A’,100), (2,’B’,200)] parentCols = [‘PID’, ‘PATTR1’, ‘PATTR1’] parentDf = pd.DataFrame.from_records(parentData, columns=parentCols) P

我是熊猫队的新手,正在尝试创建一个非规范化的平面数据集,我想知道这是否可行。我从两个数据帧开始,一个是父数据帧,另一个是子数据帧,从概念上讲,它们可以连接到一个列(“PID”)

以下是父数据帧:

parentData = [(1,’A’,100), (2,’B’,200)]
parentCols = [‘PID’, ‘PATTR1’, ‘PATTR1’]
parentDf = pd.DataFrame.from_records(parentData, columns=parentCols)

Parent Dataframe
     PID  PATTR1  PATTR2
0      1       A     100
1      2       B     200
childData = [(201,1,’AA’,2100), (202,2,’BB’,2200), (203,2,’CC’,2300)]
childCols = [‘CID’, ‘PID’, ‘CATTR1’, ‘CATTR1’]
childDf = pd.DataFrame.from_records(childData, columns=childCols)

Child Dataframe
     CID  PID  PATTR1  PATTR2
0    201    1      AA    2100
1    202    2      BB    2200
2    203    2      CC    2300
下面是子数据帧:

parentData = [(1,’A’,100), (2,’B’,200)]
parentCols = [‘PID’, ‘PATTR1’, ‘PATTR1’]
parentDf = pd.DataFrame.from_records(parentData, columns=parentCols)

Parent Dataframe
     PID  PATTR1  PATTR2
0      1       A     100
1      2       B     200
childData = [(201,1,’AA’,2100), (202,2,’BB’,2200), (203,2,’CC’,2300)]
childCols = [‘CID’, ‘PID’, ‘CATTR1’, ‘CATTR1’]
childDf = pd.DataFrame.from_records(childData, columns=childCols)

Child Dataframe
     CID  PID  PATTR1  PATTR2
0    201    1      AA    2100
1    202    2      BB    2200
2    203    2      CC    2300
下面是父级和子级的合并:

mergedDf = parentDf.merge(childDf, left_on=’PID’, right_on=’PID’, how=’outer’)

Parent merged with Child dataframe
     PID  PATTR1  PATTR2  CID  CATTR1  CATTR2
0      1       A     100  201      AA    2100
1      2       B     200  202      BB    2200
2      2       B     200  203      CC    2300
以下是所需的输出:

                          | ????                 | ????
     PID  PATTR1  PATTR2  | CID  CATTR1  CATTR2  | CID  CATTR1  CATTR2
0      1       A     100  | 201      AA    2100  |
1      2       B     200  | 202      BB    2200  | 203      CC    2300
在搜索和阅读了Pandas API文档的合并、重塑等部分后,我不确定所需的输出是否可行


非常感谢您提供的任何建议和/或帮助。

在您获得
合并DDF
后,我们将创建一个新的段落“G”,并使用
取消堆叠
(PS:这是一个很长很宽的问题)


谢谢你的帮助,这正是我所需要的@azw yw:-),快乐编码