python - 如何识别每人每次变量的变化(在面板数据中)?
问题描述
我有面板数据(每个 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)
这是我想要实现的目标:对于每个人,比较值的时间序列并丢弃与其前体值不同的每个继任者(标识红色圆圈)。然后我会尝试不同的策略来处理它:
- 丢弃(非常不确定):如果后继者不同,则丢弃它
- 平滑(绝对值):如果后继值相差(例如)1 个单位,则为其分配前导值
- 平滑(相对值):如果后继值相差(例如)1%,则为其分配前导值
掉线的解决办法
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'])
解决方案
要获取数据库中的下一个事件,您可以使用 and 的组合,groupby
然后shift
对 previos 事件进行减法运算:
df['money_difference'] =df.groupby(['year', 'id'])['money'].shift(-1)-df['money']
推荐阅读
- html - 内联块元素定位为一个固定,另一个相对
- python-2.7 - 无法在 linux mint 18 上使用 geckodriver
- wix - 使用带有自定义参数的 WIX 安装程序安装 Windows 服务
- java - 池管理器无法加载指定的驱动程序:oracle.jdbc.driver.OracleDriver
- asp.net-core - 如何在.net核心中的新登录上注销以前的登录?
- php - 从特定页面重定向到外部网站
- arrays - Spark:按字符串对列表进行排序
- forms - Access 2016:Alt+Tab...使用 Alt+Tab 在打开的表单之间切换
- spring-boot - Spring Boot:在上下文加载时间和属性更改时捕获事件
- php - 无法连接到 ssl://smtp.gmail.com:465 名称或服务未知 (0)