基于时间戳的 Python 熊猫查找值



我有一个熊猫数据帧,看起来像这样:

product month
apple  Jan-18
pear   Jan-18
banana Jan-18
apple  Jan-18
pear   Feb-18
apple  Feb-18
banana Feb-18

我创建了自己的参考表,如下所示:

id product     start       end    weight
1  apple    01/01/2011  31/01/2018 heavy
1  apple    01/02/2018  31/12/2020 small
2  banana   01/01/2015  31/01/2018 heavy
2  banana   01/02/2018  31/12/2020 small
3  pear     01/01/2016  31/12/2020 heavy

参考表始终从该月的第一天和最后几天开始。"权重"字段随着时间的推移而缓慢变化。例如,苹果和香蕉随着时间的推移而变化。日期 31/12/2020 表示此维度当前是商品的有效维度。

我需要根据时间戳将参考表中的"权重"与产品上的数据帧合并。我需要得到这个:

product month weight
apple  Jan-18 heavy
pear   Jan-18 heavy
banana Jan-18 heavy
apple  Jan-18 heavy
pear   Feb-18 heavy
apple  Feb-18 small
banana Feb-18 small

我的困难在于我不知道从哪里开始。我的数据帧和引用表中的日期字段是 datetime64[ns]

在 ref_df 中创建一个新列,其结构与 ref_df 的月份列相似

合并新创建的列上的两个数据帧

def month_conversion(x):
month_list = ['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct','Nov','Dec']
return month_list[int(x.month)-1] 
ref_df['year'] = ref_df['start'].head().map(lambda x: str(x.year)[-2:])
ref_df['month'] = ref_df.loc[0:5,'start'].map(month_conversion)
ref_df['common_key'] = ref_df['month'] +'-' +ref_df['year']
my_df['month'] = my_df['month'].astype(str)
final_df = ref_df.merge(my_df,left_on=['common_key','product'],right_index=['month','product'],suffixes=('_merge',''))

最新更新