首页 > 解决方案 > 如何识别每人每次变量的变化(在面板数据中)?

问题描述

我有面板数据(每个 ID 在不同时间点重复观察)。数据不平衡(存在差距)。多年来,我需要检查并可能调整每个人的变量变化。

我尝试了两个版本。首先,一个for循环设置,首先访问每个人和它的每一年。其次,与 . 的单行组合groupby。Groupby 对我来说看起来更优雅。这里的主要问题是确定“下一个元素”。我假设在一个循环中我可以用一个计数器来解决这个问题。

这是我的 MWE 面板数据:

import pandas as pd
df = pd.DataFrame({'year': ['2003', '2004', '2005', '2006', '2007', '2008', '2009','2003', '2004', '2005', '2006', '2007', '2008', '2009'],
                   'id': ['1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2'],
                   'money': ['15', '15', '15', '16', '16', '16', '16', '17', '17', '17', '18', '17', '17', '17']}).astype(int)
df

这是每个人的时间序列的样子:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

fig, ax = plt.subplots()

for i in df.id.unique():
    df[df['id']==i].plot.line(x='year', y='var', ax=ax, label='id = %s'%i)
    df[df['id']==i].plot.scatter(x='year', y='var', ax=ax)
    plt.xticks(np.unique(df.year),rotation=45)    

在此处输入图像描述

这是我想要实现的目标:对于每个人,比较值的时间序列并丢弃与其前体值不同的每个继任者(标识红色圆圈)。然后我会尝试不同的策略来处理它:

掉线的解决办法

df['money_difference'] = df['money']-df.groupby('id')['money'].shift(1)
df_new = df.drop(df[df['money_difference'].abs()>0].index)

平滑的想法

# keep track of change of variable by person and time
df['money_difference'] = df['money']-df.groupby('id')['money'].shift(1)
# first element has no precursor, it will be NaN, replace this by 0
df = df.fillna(0)
# now: whenever change_of_variable exceeds a threshold, replace the value by its precursor - not working so far
df['money'] = np.where(abs(df['money_difference'])>=1, df['money'].shift(1), df['money'])

标签: pythonpandasloopspandas-groupbypanel-data

解决方案


要获取数据库中的下一个事件,您可以使用 and 的组合,groupby然后shift 对 previos 事件进行减法运算:

df['money_difference'] =df.groupby(['year', 'id'])['money'].shift(-1)-df['money']

推荐阅读