在没有公共联接的情况下合并2个数据帧

2024-04-20 04:22:47 发布

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

我有只包含所有项目名称的df1和包含两列到期日和项目的df2。如何将它们组合在一起,以便生成一个数据框,其中的行名称为到期日期,并保留项目名称

df1看起来像这样

1  Index |   DueDate     

2.   0   |  1/1/2018   
3.   1   |  1/2/2018   
4.   2   |  1/2/2018      
5.   3   |  1/4/2018    
6.   4   |  1/5/2018   
7.   5   |  1/5/2018   

df2看起来像

1.   Index   |   Item1   |   Item2   |   Item 3   |    Item 4   

等等。我希望将df2的行名称设置为到期日,如下所示:

1. DueDate     Item1       |   Item2   |     Item3     |   Item4
2. 1/1/2018     
3. 1/2/2018
4. 1/3/2018
5. 1/4/2018
6. 1/5/2018

我已经尝试过将其添加为将导致类似的结果,但它使用due date列作为添加的另一列,而不是作为行名称


Tags: 数据项目名称indexitem项目名称duedf1
1条回答
网友
1楼 · 发布于 2024-04-20 04:22:47

您可以执行以下操作:

# create a pivot
df = pd.crosstab(index=df1['DueDate'], columns=df1['items']).astype(str)

# replace all values with a blank
df = df.replace(regex=r'.*', value='')

items            item1      item3      item4         item4    
DueDate                                                       
1/1/2018                                                      
1/2/2018                                                      
1/4/2018                                                      
1/5/2018     

相关问题 更多 >