按照个人ID创建虚拟变量

2024-04-26 02:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含个人和日期的时间序列数据集。我想创建一个虚拟变量“newpers”,它第一次假设值为1,按时间顺序,id显示在数据集中。例如,如果简化的数据集如下所示:

personid     yearmo
       1 2004-05-01
       1 2004-06-01
       2 2004-05-01
       2 2004-06-01

我想做的是:

personid     yearmo newpers
       1 2004-05-01       1
       1 2004-06-01       0
       2 2004-05-01       1
       2 2004-06-01       0

抱歉,如果这很简单,但我一直在兜圈子,我被难住了。我一直在试着对每个人进行分组/排序,以确定他们的第一次约会。伪变量可以是newpers=(yearmo==firstmo),但我似乎无法让groupby/sort不抛出错误。你知道吗


Tags: 数据id排序顺序错误时间序列sort
2条回答

我将使用shift方法在数据帧中向后看:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'A': [1, 1, 1, 2, 2, 3, 3, 3, 3, 3], 
    'B': np.random.random_integers(low=0, high=10, size=10)
})
df['A_'] = df['A'].shift()  # each row will contain the previous value of A
df['new_A'] = df.apply(lambda row: int(row['A'] != row['A_']), axis=1)

   A   B  A_  new_A
0  1  10 NaN      1
1  1   3   1      0
2  1   8   1      0
3  2   6   1      1
4  2   4   2      0
5  3   2   2      1
6  3   4   3      0
7  3   1   3      0
8  3   0   3      0
9  3   1   3      0

这应该有效(假设按personid、yearmo排序)

df['newpers'] = df.personid != df.personid.shift(1)

相关问题 更多 >