[英]Pandas_data frame/Python : How to sort a data frame column based on its highest repeated value count?
我有一個數據框如下
import pandas as pd
df = pd.DataFrame({'UserId': [1,2,2,3,3,3,4,4,4,4], 'Value': [1,2,3,4,5,6,7,8,9,0]})
print(df)
現在,我想根據其最高重復值對UserId列進行排序/顯示。 在上述數據幀中,順序為4、3、2、1。 現在我的預期輸出如下
df = pd.DataFrame({'UserId': [4,4,4,4,3,3,3,2,2,1], 'Value': [7,8,9,0,4,5,6,2,3,1]})
print(df)
在這里,我手動進行。 我需要大型數據框值的代碼。 指導我的情況。 提前致謝。
您可以首先獲取每個UserId
的計數:
>>> counts = df.UserId.value_counts()
>>> counts
4 4
3 3
2 2
1 1
Name: UserId, dtype: int64
然后,您可以創建一個新列來指示每個用戶的UserId
計數(也可以通過合並來完成):
>>> df['UserIdCount'] = df['UserId'].apply(lambda x: counts.loc[x])
>>> df
UserId Value UserIdCount
0 1 1 1
1 2 2 2
2 2 3 2
3 3 4 3
4 3 5 3
5 3 6 3
6 4 7 4
7 4 8 4
8 4 9 4
9 4 0 4
然后,您只需按此列排序即可:)
>>> df = df.sort_values('UserIdCount', ascending=False)
>>> df
UserId Value UserIdCount
6 4 7 4
7 4 8 4
8 4 9 4
9 4 0 4
3 3 4 3
4 3 5 3
5 3 6 3
1 2 2 2
2 2 3 2
0 1 1 1
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.