Python- Pandas : select first observation per group

标签 python pandas dataframe

我想使用 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)10对于其他人。数据集如下所示:

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/

相关文章:

python - Pandas DataFrame 中连续的 NaN 大于阈值

python - Python 中的堆栈和数据透视数据框

javascript - Django Admin 根据其他选择动态禁用字段

python - 将带有索引的 numpy 数组转换为 pandas 数据框

python - Pandas:扩展掩码以设置区域

python - 对 DataFrame 内存进行排序是否高效?

python - 保存混淆矩阵

r - 在 R 中查找数据框中的序列

python - 如何设置一个具有所有方法和功能的类,如内置的 float,但保留额外的数据?

Python 3 博托 3,AWS S3 : Get object URL