Skip to main content
 首页 » 编程设计

python之折叠 Pandas 数据框数据集中的行

2025年01月19日9三少

我是 Pandas 的新手,我正在尝试创建一个非规范化的平面数据集,并想评估它是否可行。我从两个数据框开始,一个是父数据框,一个是子数据框,它们在概念上可以连接到一个列(“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 

这是父子的合并:

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 文档的合并、 reshape 等部分后,我不确定是否可以得到所需的输出。

在此先感谢您的任何建议和/或帮助,非常感谢。

请您参考如下方法:

在你得到 mergedDf 之后,我们创建一个新的 para 'G' 并使用 unstack(PS:这是一个从长到宽的问题)

mergedDf.assign(G=mergedDf.groupby('PID').cumcount())\ 
     .set_index(['PID','PATTR1','PATTR2','G'])\ 
       .unstack().swaplevel(0,1,1)\ 
               .sort_index(1,level=0) 
Out[218]:  
G                      0                     1                
                  CATTR1  CATTR2    CID CATTR1  CATTR2    CID 
PID PATTR1 PATTR2                                             
1   A      100        AA  2100.0  201.0   None     NaN    NaN 
2   B      200        BB  2200.0  202.0     CC  2300.0  203.0