在 Python 中通过 ID 获取第一行

问题描述 投票:0回答:2

我有一段代码应该获取按 ID 分组的列的

first_team
(第一个值)并将其设置为字典,但我看到的是它只获取第一个值。不包括那些 NaN.

这是一个示例数据集

 ID     date           name       team       first_team
 101   05/2012         James      NaN            NY
 101   07/2012         James      NY             NY
 102   06/2013         Adams      NC             NC
 102   05/2014         Adams      AL             NC 

我的代码是:

first_dict = df.groupby('ID').agg({'team':'first'}).to_dict()['team']
df['first_team'] = df['ID'].apply(lambda x: first_dict[x])

期望的输出:

  ID      date        name      team         first_team 
  101     05/2012     James      NaN           NaN 
  101     07/2012     James      NY            NaN 
  102     06/2013     Adams      NC            NC 
  102     05/2014     Adams      AL            NC 
python python-3.x pandas dataframe group-by
2个回答
2
投票

如果你想保留第一个条目,你可以用

drop_duplicates

first_dict = df.drop_duplicates('ID')[['ID','team']].set_index('ID')['team']
df['first_team'] = df['ID'].map(first_dict)

输出:

    ID     date   name team first_team
0  101  05/2012  James  NaN        NaN
1  101  07/2012  James   NY        NaN
2  102  06/2013  Adams   NC         NC
3  102  05/2014  Adams   AL         NC

注意:FFR,您的代码可以用

transform

更好地完成
df['first_team'] = df.groupby('ID')['team'].transform('first')

0
投票

你只得到每个组的第一个非 NA 值的原因是因为带有 'first' 参数的 agg 函数返回组中的第一个非 NA 值。要获取第一个值而不管它是否为 NA,可以使用索引为 0 的 iloc 方法而不是 agg 函数。这是更新后的代码:

first_dict = df.groupby('ID')['team'].apply(lambda x: x.iloc[0]).to_dict()
df['first_team'] = df['ID'].apply(lambda x: first_dict.get(x))

希望对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.