Python 如何基于某些逻辑连接2个数据帧

Python 如何基于某些逻辑连接2个数据帧,python,pandas,dataframe,join,left-join,Python,Pandas,Dataframe,Join,Left Join,我有一个包含以下每两周一次数据的数据框 date value 15-06-2012 20 30-06-2012 30 我需要加入另一个具有以下数据的数据帧: date cost 2-05-2011 5 3-04-2012 80 2-06-2012 10 3-06-2012 10 4-06-2012 30 5-06-20

我有一个包含以下每两周一次数据的数据框

date            value
15-06-2012      20
30-06-2012      30
我需要加入另一个具有以下数据的数据帧:

   date            cost
    2-05-2011       5
    3-04-2012       80
    2-06-2012       10
    3-06-2012       10
    4-06-2012       30
    5-06-2012       20
    10-06-2012      10
    15-06-2012      10
    18-06-2012      30
    20-06-2012      20
    21-06-2012      30
    22-06-2012      30
    29-06-2012      20
    29-10-2012      30
我需要以这样的方式连接两个数据帧:从另一个数据帧,我得到2012年6月1日至15日之间的平均成本,以填充2012年6月15日的成本;同样,对于2012年6月30日的成本,我得到2012年6月16日至2012年6月30日之间的平均值,并得到以下结果

 date            value cost
15-06-2012      20     15  which is (10+10+30+20+10+10)/6
30-06-2012      30     26  which is (30+20+30+30+20)/5

这将需要一个
合并
,然后是一个
分组比

m = df.merge(df2, on='date', how='outer')
m['date'] = pd.to_datetime(m.date, dayfirst=True)
m = m.sort_values('date')

(m.groupby(m['value'].notnull().shift().fillna(False).cumsum(), 
           as_index=False)
  .agg({'date' : 'last', 'cost' : 'mean', 'value' : 'last'}))

        date  cost  value
0 2012-06-15  15.0   20.0
1 2012-06-30  26.0   30.0

将列日期更改为datetime,然后我们使用
merge\u asof

#df.date=pd.to_datetime(df.date,dayfirst=True)
#df1.date=pd.to_datetime(df1.date,dayfirst=True)
df['keepkey']=df.date
mergedf=pd.merge_asof(df1,df,on='date',direction ='forward')
mergedf.groupby('keepkey',as_index=False).mean()
Out[373]: 
     keepkey  cost  value
0 2012-06-15    15     20
1 2012-06-30    26     30
更新:

df['keepkey']=df.date
df['key']=df.date.dt.strftime('%Y-%m')
df1['key']=df1.date.dt.strftime('%Y-%m')
mergedf=pd.merge_asof(df1,df,on='date',by='key',direction ='forward')
mergedf.groupby('keepkey',as_index=False).mean()
Out[417]: 
     keepkey  cost  key  value
0 2012-06-15    15    6   20.0
1 2012-06-30    26    6   30.0

您好,通过在我的实际数据中使用此项,我得到了不正确的成本,即2012年6月15日的成本为2012年6月16日的成本,没有平均值,知道吗?在我的实际数据中,日期列名称不同,所以我使用left_on和right_on,并根据left_on进行分组column@user3222101我的df1是你的第二个df。df是您的第一个dfyeah相同的wen,实际数据不同,但它包含相同的格式,您认为2个数据帧中日期的不同列名可能会有问题吗?啊,明白了,当我加入时,它考虑了2012年6月15日之前的所有日期,但我只需要取2012年6月1日到2012年6月15日之间的数据,同时取一点平均值和修改后的数据,请你解决一下这个问题,因为它给了你一个答案results@user3222101在merge\u asof中使用
by
检查更新