Python-Pandas数据框:对大于或等于数据框中值的值进行计数

时间:2019-11-07 14:31:00

标签: python pandas

我想为数据框中的列中的每个值计数,有多少个值大于或等于该列中的值。然后我想将此计数值存储在数据框中的新列中。

1 个答案:

答案 0 :(得分:0)

我认为您想要这样的东西:

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最大值用于为重复项分配相同的值。