我想使用 dataframe
将我以前的 SAS 代码改编为 Python框架。
在 SAS 中,我经常使用这种类型的代码(假设列按 group_id 排序,其中 group_id 取值 1 到 10,其中每个 group_id 有多个观察值):
data want;set have;
by group_id;
if first.group_id then c=1; else c=0;
run;
所以这里发生的是,我为每个 id 选择第一个观察值,并创建一个新变量 c
这需要值(value)1
和0
对于其他人。数据集如下所示:
group_id c
1 1
1 0
1 0
2 1
2 0
2 0
3 1
3 0
3 0
如何使用 dataframe
在 Python 中执行此操作?假设我从 group_id
开始仅矢量。
最佳答案
如果您使用的是 0.13+,则可以使用 cumcount
分组方法:
In [11]: df
Out[11]:
group_id
0 1
1 1
2 1
3 2
4 2
5 2
6 3
7 3
8 3
In [12]: df.groupby('group_id').cumcount() == 0
Out[12]:
0 True
1 False
2 False
3 True
4 False
5 False
6 True
7 False
8 False
dtype: bool
您可以强制数据类型为 int 而不是 bool:
In [13]: df['c'] = (df.groupby('group_id').cumcount() == 0).astype(int)
关于Python- Pandas : select first observation per group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21591326/