Skip to main content
 首页 » 编程设计

Python:为DataFrame中每个组的第一个观察值赋值

2025年05月04日15lexus

为什么在 Python 中,使用 Pandas,我们不能使用以下代码为每个组的第一个观察值赋值?

df['A'].groupby(df.ID).first()==0 
 
or 
 
df['A'].groupby(df.ID).first()==np.nan 

DataFrame 的样子:

ID  A   
1   2 
1   1 
1   .45 
2   .14 
2   3 
2   4 

换句话说,我想要

ID  A   
1   0 or NaN 
1   1 
1   .45 
2   0 or NaN 
2   3 
2   4 

cumcount 对我不起作用,尽管我已经安装了 Pandas 0.13。与其他人一样,Pandas 0.13 安装时出现错误,我想避免处理 Pandas 0.13。

请您参考如下方法:

In [24]: df = read_csv(StringIO(data),sep='\s+') 
 
In [25]: df 
Out[25]:  
   ID     A 
0   1  2.00 
1   1  1.00 
2   1  0.45 
3   2  0.14 
4   2  3.00 
5   2  4.00 
 
[6 rows x 2 columns] 
 
In [26]: df.loc[df.groupby('ID',as_index=False).head(1).index,'A'] = np.nan 
 
In [27]: df 
Out[27]:  
   ID     A 
0   1   NaN 
1   1  1.00 
2   1  0.45 
3   2   NaN 
4   2  3.00 
5   2  4.00 
 
[6 rows x 2 columns]