[英]Unique values within Pandas group of groups
我有一個我需要分組的數據幀,然后是子組。 從子組我需要返回子組的內容以及列的唯一值。
df = pandas.DataFrame({'country': pandas.Series(['US', 'Canada', 'US', 'US']),
'gender': pandas.Series(['male', 'female', 'male', 'female']),
'industry': pandas.Series(['real estate', 'shipping', 'telecom', 'real estate']),
'income': pandas.Series([1, 2, 3, 4])})
def subgroup(g):
return g.groupby(['gender'])
s = df.groupby(['country']).apply(subgroup)
從s開始,我如何計算“行業”的獨特性以及它所分組的“性別”?
--------------------------------------------
| US | male | [real estate, telecom] |
| |----------------------------------
| | female | [real estate] |
--------------------------------------------
| Canada | female | [shipping] |
--------------------------------------------
你不需要定義那個函數,你可以用groupby()和unique()來解決你的問題;
嘗試:
df.groupby(['country','gender'])['industry'].unique()
輸出:
country gender
Canada female [shipping]
US female [real estate]
male [real estate, telecom]
Name: industry, dtype: object
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.