python - 如何在python中按有序数字1、123、12、12 ..等进行分组
问题描述
我有一个有 3303 行的数据。我在 python 中使用熊猫
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],'B': ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'], 'C': np.random.randn(8),'D': np.random.randn(8), 'E':['1','1','2','3','1','2','1','2',]})
OUTPUT:
A B C D E
0 foo one -1.607303 1.343192 1
1 bar one 2.064340 1.000130 1
2 foo two -0.362983 1.113389 2
3 bar three 0.486864 -0.804323 3
4 foo two 0.111030 -0.322696 1
5 bar two -0.729870 0.912012 2
6 foo one 1.111405 0.076317 1
7 foo three 0.378172 0.298974 2
您知道如何按数字顺序对“E”列进行分组吗?意义; 关于如何按迭代进行分组的任何想法,例如第一组中的 1,2,3,第二组中的 1,2,第三组中的 1,第四组中的 1,2……等等,这样就会像
A B C D E G
0 foo one -1.607303 1.343192 1 a
1 bar one 2.064340 1.000130 1 b
2 foo two -0.362983 1.113389 2 b
3 bar three 0.486864 -0.804323 3 b
4 foo two 0.111030 -0.322696 1 c
5 bar two -0.729870 0.912012 2 c
6 foo one 1.111405 0.076317 1 d
7 foo three 0.378172 0.298974 2 d
这样它就像新列“H”、“I”具有按“G”分组的“C”和“D”值之和。请在这部分建议和指导我
解决方案
尝试这个:
df['G'] = df.E.eq('1').cumsum()
如果每个新组都以“1”开头,则此方法有效。如果不是,您需要求助于yatu 的解决方案。
要回答您的整个问题:
df[['H','I']] = df.groupby(df.E.eq('1').cumsum())[['C','D']].transform(sum)
推荐阅读
- visual-studio - Visual Studio 代码中的文本换行和电子邮件选项
- mysql - 如何更新orders_food表中的total_price,该表通过food_id连接到food_items表,其中包含食品价格
- performance - 测试 Intel Extension for Pytorch(IPEX) 从 huggingface / transformers 中的多项选择
- reactjs - 设定值中的原型污染
- android - 如何在 Android Studio 中使用 FCM 令牌向设备发送通知?
- angular - 当控件的值发生变化时,角度 seterrors 会发生变化
- javascript - 我想在单击按钮时显示段落内容 5 分钟,即使在使用 javascript 在 Java 代码中刷新页面时也是如此
- go - go fiber slice append 更改所有项目
- python - 如何增加 Docker 的日志限制?| [输出剪辑,日志限制达到 100KiB/s]
- visual-studio-code - VSCode 扩展:命令“Hello World”导致错误(未找到命令“vscode-err-reproduce.helloWorld”)