簡體   English   中英

如何確定每個人每次變量的變化(面板數據)?

[英]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)    

在此處輸入圖片說明

這是我要實現的目標 :對於每個人,比較值的時間序列,並丟棄每個與其前驅值不同的繼任者(標識紅色圓圈)。 然后,我將嘗試不同的策略來處理它:

  • 丟棄(非常不穩定):如果后繼者不同,則丟棄
  • 平滑(絕對值):如果后繼者相差(例如)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'])

要獲取數據庫中的下一個事件,可以將groupbyshift結合使用,然后對previos事件進行替換:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM