[英]How to identify changes in a variable per person per time (in panel data)?
我有面板数据(每个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'])
要获取数据库中的下一个事件,可以将groupby
和shift
结合使用,然后对previos事件进行替换:
df['money_difference'] =df.groupby(['year', 'id'])['money'].shift(-1)-df['money']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.