分组值

时间:2017-02-27 15:06:29

标签: python pandas numpy

我的数据框包含3列,Id,Stage,Status。我想根据条件更改该值:如果对于相同的ID,则更改阶段,然后将状态更改为1.如果发生了相同ID的另一个事件,则阶段仍然相同,然后将状态更改回0。 / p>

谢谢!

3 个答案:

答案 0 :(得分:2)

要计算 Period 列,您可以使用两个(嵌套) groupby 来计算结果:

df["Period"] = (df.groupby("ID", group_keys=False)
                  # use the common diff.cumsum pattern to calculate the group variable here
                  .apply(lambda g: g.groupby(by = (g.Stage.diff() != 0).cumsum())
                                    .cumcount() * 30))
df

enter image description here

答案 1 :(得分:1)

可以通过以下方式获取状态列:

df.groupby('ID').diff().Stage.fillna(0).ne(0)
Out[86]: 
4     False
10     True
0     False
2      True
3      True
5      True
7     False
8     False
9      True
1     False
6     False
Name: Stage, dtype: bool

答案 2 :(得分:0)

您需要对列ID进行排序,然后使用np.where()df.shift()来查找正确的状态。

df=df.sort_values('ID')

df['Status']=np.where(((df.ID.shift()==df.ID) & (df.Stage.shift()<>df.Stage)),1,0)

输出

    ID  Stage  Status  
4   45      2       0  
10  45      3       1  
0   50      4       0  
2   50      5       1  
3   50      6       1  
5   50      4       1  
7   50      4       0  
8   50      4       0  
9   50      5       1  
1   55      3       0  
6   55      3       0  
相关问题