簡體   English   中英

如何根據最小值對行進行排序並在 Pandas 中替換它們?

[英]How can I sort rows according minimum values and replace them in Pandas?

假設我有一個 DataFrame:

import pandas as pd

dict1 = {'Name':['John', 'Sean', 'Philip', 'John', 'Sean', 'Philip'],
     'c_1':['a','b','c','d','f','g'],
     'c_2':[1,2,3,4,2,3],
     'c_3':[2,3,4,2,1,1]} 

df = pd.DataFrame(dict1)

和 output:

     Name c_1  c_2  c_3
0    John   a    1    2
1    Sean   b    2    3
2  Philip   c    3    4
3    John   d    4    2
4    Sean   f    2    1
5  Philip   g    3    1

所需 output:

     Name c_1  c_2  c_3
0    John   a    1    2
1    Sean   f    2    1
2  Philip   g    3    1

我需要為每個名稱找到具有最小值 c_1 和 c_2 的行。
c_1 具有高優先級(這意味着 (c_1 = 1) & (c_2 = 2) 比 (c_1 = 2) & (c_2 = 1) 更重要(和必需))。
我嘗試使用循環,但沒有成功,因為我有巨大的 DF,而我的電腦會長時間這樣做。

我怎樣才能以最簡單的方式做到這一點?

非常感謝您的回答!

您可以使用sort_values

df.sort_values(['Name','c_2','c_3']).groupby('Name').agg('first')

       c_1  c_2  c_3
Name                
John     a    1    2
Philip   g    3    1
Sean     f    2    1

如果要保留名稱的順序,請將列轉換為categorical

df['Name'] = pd.Categorical(df.Name, categories=df.Name.unique())
df.sort_values(['Name','c_2','c_3']).groupby('Name').agg('first')

       c_1  c_2  c_3
Name                
John     a    1    2
Sean     f    2    1
Philip   g    3    1

暫無
暫無

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

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