基于时间戳的Python查找值

2024-04-19 14:49:04 发布

您现在位置: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意味着这是当前产品的活动维度。你知道吗

我需要根据时间戳将引用表中的“weight”与产品上的数据帧合并。我需要得到这个:

 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]


Tags: 数据idapple产品时间productstartjan
1条回答
网友
1楼 · 发布于 2024-04-19 14:49:04

在ref\u df中创建一个新列,其结构与ref\u df的month列相似

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

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',''))

相关问题 更多 >