簡體   English   中英

Python-Pandas Dataframe:計數值大於或等於 dataframe 中的值

[英]Python-Pandas Dataframe: count values greater than or equal to a value in the dataframe

我想對dataframe中的列中的每個值進行計數,該列中有多少值大於或等於該值。 然后我想將此計數值存儲在 dataframe 的新列中。

我想你想要這樣的東西:

df=pd.DataFrame({'values':[1,4,3,23,6,7,8,22,55,43,10,4]})



mapper=( df['values'].sort_values(ascending=False)
                     .reset_index(drop=True)
                     .reset_index()
                     .drop_duplicates('values',keep='last')
                     .set_index('values')['index'] )
df['Greater than value']=df['values'].map(mapper)
print(df)

    values  Greater than value
0        1                  11
1        4                   9
2        3                  10
3       23                   2
4        6                   7
5        7                   6
6        8                   5
7       22                   3
8       55                   0
9       43                   1
10      10                   4
11       4                   9

df=pd.DataFrame({'values':[1,4,3,23,6,7,8,22,55,43,10,4]})
counts = ( (df.sort_values('values',ascending=False)
              .expanding().count()-1).sort_index() 
                                     .groupby(df['values'])                                                              
                                     .transform('max') )


df=df.assign(greater_than_value=counts)
print(df)
    values  greater_than_value
0        1                11.0
1        4                 9.0
2        3                10.0
3       23                 2.0
4        6                 7.0
5        7                 6.0
6        8                 5.0
7       22                 3.0
8       55                 0.0
9       43                 1.0
10      10                 4.0
11       4                 9.0

這里transform max 用於將相同的值分配給重復項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM