首页 > 解决方案 > 使用 groupby 查找往年信息

问题描述

我正在使用具有以下形式的熊猫数据框:

df = pd.DataFrame({'year': [2016,2017,2017,2018,2019,2017,2018,2019,2018,2019],
                  'Name':['A','A','A','A','A','B','B','B','C','C'],
                  'It':[1,1,2,1,1,1,1,1,1,1],
                  'Val1':[5,8,1,1,4,2,6,2,7,10]})

我正在尝试根据前几年的数据进行某种建模来预测 Val1。为此,我想创建一个新的数据框,该数据框将具有相同的确切索引和名称,但它将具有第 1 年的 Val1。“它”也有不同的可能性(客户迭代,1 表示他们在系统中一年 1 次,2 表示 2 次,依此类推。

我的方法如下。我遍历行,尝试匹配名称和年份列,检查它是否为空或每年是否有多个客户。

这是非常缓慢的。我的实际应用程序有另一个 df 被搜索(在我的循环中它将是df['Val2'] = otherDF.loc(otherDF.name ==rows.Name)- 我目前正在研究合并)。
但是这种方法很慢,我想知道我是否可以利用 groupby 并转移来提取上一年的信息(但是如何填写?

list_of_frames = []
for rows in df.itertuples():
temp = df.loc[(df.Name==rows.Name) & (df.year == rows.year-1),:]
#Check if It exists
if temp.empty:  #Fill Values with Zeros For Now
    temp.loc[0,'Name'] = rows.Name
    temp['year'] = rows.year-1
    temp['It'] = 1
    temp['Val1'] = 0
    temp.index = [rows.Index]
    list_of_frames.append(temp)

else:
    #Check how many times they appear
    if len(temp.index) != 1: 
    # Just add the data together
        temp = temp.groupby(['Name','year']).agg('sum').reset_index(drop=False)

        temp['year'] = rows.year-1
        temp['It'] = 1
        temp.index = [rows.Index]    
        list_of_frames.append(temp)

    else :

        temp.index = [rows.Index] 
        list_of_frames.append(temp)

last_year_data = pd.concat(list_of_frames,sort=False).drop_duplicates().reset_index(drop=True)

标签: pythonpandaspandas-groupby

解决方案


推荐阅读