亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何分組并獲得三個最頻繁的值?

如何分組并獲得三個最頻繁的值?

汪汪一只貓 2023-05-16 09:46:27
我想按 id 分組并獲得三個最常見的城市。例如我有原始數據框  ID    City    1    London    1    London    1    New York    1    London    1    New York    1    Berlin    2    Shanghai    2    Shanghai我想要的結果是這樣的:ID first_frequent_city   second_frequent_city   third_frequent_city1   London               New York               Berlin2   Shanghai             NaN                    NaN
查看完整描述

4 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

第一步是使用perSeriesGroupBy.value_counts的計數值,優點是已經對值進行了排序,然后通過 獲取計數器,通過 過濾第一個值,通過 旋轉,更改列名并最后轉換為列:CityIDGroupBy.cumcount3locDataFrame.pivotIDDataFrame.reset_index

df = (df.groupby('ID')['City'].value_counts()

? ? ? ? .groupby(level=0).cumcount()

? ? ? ? .loc[lambda x: x < 3]

? ? ? ? .reset_index(name='c')

? ? ? ? .pivot('ID','c','City')

? ? ? ? .rename(columns={0:'first_', 1:'second_', 2:'third_'})

? ? ? ? .add_suffix('frequent_city')

? ? ? ? .rename_axis(None, axis=1)

? ? ? ? .reset_index())

print (df)

? ?ID first_frequent_city second_frequent_city third_frequent_city

0? ?1? ? ? ? ? ? ? London? ? ? ? ? ? ?New York? ? ? ? ? ? ? Berlin

1? ?2? ? ? ? ? ? Shanghai? ? ? ? ? ? ? ? ? NaN? ? ? ? ? ? ? ? ?NaN


查看完整回答
反對 回復 2023-05-16
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

另一種使用count作為排序參考的方法,然后通過遍歷groupby對象重新創建數據框:


df = (df.assign(count=df.groupby(["ID","City"])["City"].transform("count"))

        .drop_duplicates(["ID","City"])

        .sort_values(["ID","count"], ascending=False))

    

print (pd.DataFrame([i["City"].unique()[:3] for _, i in df.groupby("ID")]).fillna(np.NaN))


          0         1       2

0    London  New York  Berlin

1  Shanghai       NaN     NaN


查看完整回答
反對 回復 2023-05-16
?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

獲取.countby ID,City然后np.where()與.groupby()withmax和median一起使用min。然后將索引和取消堆疊行設置為列上的列max。


df = df.assign(count=df.groupby(['ID', 'City'])['City'].transform('count')).drop_duplicates()

df['max'] = np.where((df['count'] == df.groupby('ID')['count'].transform('min')), 'third_frequent_city', np.nan)

df['max'] = np.where((df['count'] == df.groupby('ID')['count'].transform('median')), 'second_frequent_city', df['max'])

df['max'] = np.where((df['count'] == df.groupby('ID')['count'].transform('max')), 'first_frequent_city', df['max'])

df = df.drop('count',axis=1).set_index(['ID', 'max']).unstack(1)

輸出:


    City

max first_frequent_city second_frequent_city    third_frequent_city

ID          

1   London              New York                Berlin

2   Shanghai            NaN                     NaN


查看完整回答
反對 回復 2023-05-16
?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

有點長,基本上你 groupby 兩次,第一部分基于分組按升序對數據進行排序的想法,第二部分允許我們將數據拆分為單獨的列:


(df

.groupby("ID")

.tail(3)

.drop_duplicates()

.groupby("ID")

.agg(",".join)

.City.str.split(",", expand=True)

.set_axis(["first_frequent_city",

           "second_frequent_city", 

           third_frequent_city"],

           axis="columns",)

)



     first_frequent_city    second_frequent_city    third_frequent_city

ID          

1      London                 New York                Berlin

2      Shanghai               None                    None


查看完整回答
反對 回復 2023-05-16
  • 4 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號