我正在嘗試獲取python資料集中每個變數的最常見值。例如,我想知道每個城市的人最常喜歡的顏色。
data = {'Name':['Tom', 'nick', 'krish', 'jack', 'John', 'Bettany', 'Leo', 'Aubrie', 'Martha', 'Grant'],
'Age':[20, 21, 19, 18,24,25,26,26,27, 25],
'Prefered color':['green', 'green', 'red', 'blue', 'white', 'black', 'green', 'blue', 'red', 'white'],
'state':['Utah', 'Utah', 'Idaho', 'California', 'Texas', 'Arizona', 'Idaho', 'California', 'Idaho', 'Texas'] }
df = pd.DataFrame(data)
df
我希望看到這樣的表格:
Utah - Green
Idaho - Red
Texas - White
Arizona - Blue
uj5u.com熱心網友回復:
嘗試使用groupby和mode。由于一個系列可以有多種模式,您可以連接:
>>> df.groupby("state")["Prefered color"].agg(lambda x: x.mode().str.cat(sep=","))
state
Arizona black
California blue,red
Idaho blue,green,red
Texas white
Utah green
Name: Prefered color, dtype: object
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476499.html
上一篇:Python:如果未將變數傳遞給函式,則訪問類函式之外的變數
下一篇:洗掉單個字符子字串且不在串列中
