簡體   English   中英

我的數據中帶有 NaN 的 Pandas nlargest 返回超過 n 行數據

[英]Pandas nlargest with NaN inside my data return more than n rows of data

我的DataFrame看起來像這樣:

  Name  Score1  Score2  Score3
0    A      98      72      99
1    A      98      84      91
2    B      34      20      81
3    A      98      93      88
4    B      68      97      12
5    A     NaN      72     NaN

我想按名稱Score1 groupby取前 2 名,如果重復值,則查看Score2中較大的一個。 期待:

  Name  Score1  Score2  Score3
0    A      98      93      88
1    A      98      84      91
2    B      68      97      12
3    B      34      20      81

我試過df.groupby("Name").apply(lambda x:x.nlargest(2, ["Score1", "Score2"])).reset_index(drop=True) 我得到的是:

  Name  Score1  Score2  Score3
0    A     98      93      88
1    A     98      84      91
2    A     98      72      99
3    A    NaN      72     NaN
4    B     68      97      12
5    B     34      20      81

我發現由於NaN ,它為Name A返回了超過 2 行的數據。 dropna是修復它的唯一方法嗎?

你也可以這樣做:

out = df.sort_values(['Score1', 'Score2'], ascending=False).groupby('Name').head(2)
print(out)
  Name  Score1  Score2  Score3
3    A    98.0      93    88.0
1    A    98.0      84    91.0
4    B    68.0      97    12.0
2    B    34.0      20    81.0

您可以在使用 nlargest 之前嘗試填充 nan 或刪除它們。

cols = ["Score1", "Score2"]

df[cols] = df[cols].fillna()
#df = df.dropna(subset=columns)

out = df.groupby("Name").apply(lambda g: g.nlargest(2, cols)).reset_index(drop=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM