![](/img/trans.png)
[英]How to find column values which contains unique value in another column from same dataframe?
[英]Pandas Dataframe: Find unique value from one column which has the largest number of unique values in another column
我有以下 pandas dataframe
df = pd.DataFrame([[99, 88, 88, 66, 66, 99, 66, 77, 77, 77, 66, 66, 99, 99], list('DAABBBBABCBDDD'), ['***','**','****','*','***','*','**','***','*','*','****','**','**','****']]).T
df.columns = ['col1','col2','col3']
假設 col1 是公司,col2 是產品類型。 我正在尋找擁有最多不同產品類型的公司。
所以我正在尋找 col1 中的哪個唯一值在 col2 中具有最大數量的唯一值
我嘗試了以下方法:
df.groupby(['col1'])['col2'].nunique()
返回:
col1
66 2
77 3
88 1
99 2
現在我想從 col1 中獲取 col2 中最高值的值。 這是:
77 3
我努力了
df.groupby(['col2'])['col1'].nunique().max()
但是我只收到 col2 中唯一值的最大值
3
相反,我想知道 col2 的最大值和 col1 中的哪個值。 IE
77 3
謝謝您的幫助!
我想知道 col2 的最大值和 col1 中的哪個值。
根據您的結果,同時調用:
result = df.groupby(['col1'])['col2'].nunique()
result.idxmax() # 77
result.max() # 3
您也可以在調用.loc[lambda d: d.idxmax()]
之前將其轉換為 DataFrame 但我不知道您為什么要這樣做。
嘗試這個,
grouped=pd.DataFrame(df.groupby(['col1'])['col2'].nunique()).reset_index()
grouped[grouped['col2'] == grouped["col2"].max()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.