Concat数据帧以顺序方式

问题描述 投票:0回答:2

我有一个这样的数据框:

df1:

  start_date  end_date
0 20180101    20181231
1 20170101    20171231

另一个这样的数据框:

df2:

   Type    Value
0  House   100
1  Car     200
2  Bus     300
3  House   150 
4  Car     220  
5  Bus     320 

我需要以某种方式将df1的第一个值(start_date 20180101和end_date 20181231)应用于df2的类型的第一轮,并将其应用于第二轮至第二轮的方式,依此类推(以此类推(首次出现“ House”)具有开始日期20180101和结束日期20181231;第二次出现“房屋”时,它应具有开始日期20170101和结束日期20171231,依此类推。它看起来应该像这样:

df3:

   Type    Value  start_date  end_date
1  House   100    20180101    20181231
2  Car     200    20180101    20181231
3  Bus     300    20180101    20181231
4  House   150    20170101    20171231
5  Car     220    20170101    20171231
6  Bus     320    20170101    20171231

有什么想法吗?

python pandas dataframe
2个回答
3
投票

首先,我们在rounds中创建df2列,该列指示House再次出现时的单独回合。

然后我们在rounds中也为每一行创建一个df1列。

最后是我们在merge列上的rounds

df2['rounds'] = df2['Type'].eq('House').cumsum()
df1['rounds'] = df1.index + 1

df2 = df2.merge(df1, on='rounds', how='left').drop(columns='rounds')

输出

    Type  Value  start_date  end_date
0  House    100    20180101  20181231
1    Car    200    20180101  20181231
2    Bus    300    20180101  20181231
3  House    150    20170101  20171231
4    Car    220    20170101  20171231
5    Bus    320    20170101  20171231

注意

我假设您的df1 index1开头,如果它以0开头,则删除+1


1
投票

让我们使用cumcount

df2.assign(index=df2.groupby('Type').cumcount()).\
      merge(df1.reset_index(),on='index').drop('index',1)
Out[59]: 
    Type  Value  start_date  end_date
0  House    100    20180101  20181231
1    Car    200    20180101  20181231
2    Bus    300    20180101  20181231
3  House    150    20170101  20171231
4    Car    220    20170101  20171231
5    Bus    320    20170101  20171231
© www.soinside.com 2019 - 2024. All rights reserved.