python - Python-Pandas 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 用于为重复项分配相同的值。
推荐阅读
- sql - 如何增强查询以使其运行速度更快,时间更短?
- python - 使用 on_touch_down() 在 Kivy 中交换小部件/替换布局
- firebase - 当我的应用程序在 react native firebase 中关闭时,推送通知不起作用
- mysql - 在 RDS MySQL5.7 T3.xlarge 实例中完全空闲时 CPU 使用率为 20%
- java - Wildfly:如何将 VFS URL 解析为物理 URL?
- xcode - Xamarin.iOS 支持 XCode 11.6?
- typescript - 有没有办法检查接口是否是联合类型的一部分?
- ruby-on-rails - 如何使用 Minitest on Rails 6 测试 301 重定向
- sqlite - 如何在 Flutter 中将 PDF 编码为二进制文件
- google-apps-script - 无法为选择表单附加选项