4 回答

TA貢獻1834條經驗 獲得超8個贊
第一步是使用perSeriesGroupBy.value_counts
的計數值,優點是已經對值進行了排序,然后通過 獲取計數器,通過 過濾第一個值,通過 旋轉,更改列名并最后轉換為列:City
ID
GroupBy.cumcount
3
loc
DataFrame.pivot
ID
DataFrame.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

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

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

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
添加回答
舉報