python - 在 Python 中按多个条件对数据进行分组
问题描述
我想我有一个快速的问题,但我没有找到用简单的话谷歌搜索它的方法。
我有一个像这样的原始数据集:
Number of account Value
123 100
456 300
789 400
910 100
674 250
我有一个方法表可以将这些原始数据整合成有用的东西。看起来像:
Variable Number of account
"a" 123, 456, 910
"b" 789,674
所以,最后我想得到一张这样的桌子:
Variable Number of account
"a" Sum of values for(123, 456, 910)
"b" Sum of values for(789,674)
我最初的想法是做类似的事情:对于方法表中的每一行,对于方法表中的每个帐户数,原始数据中的总和值。
两个问题:
- 巩固它的最佳方法是什么?
- 如果方法表中的账户数是逗号分隔的字符串怎么办?(“123,456,910”)。我可以在 pandas DataFrame 的一个单元格中存储多个数字吗
解决方案
假设我在两个数据框中有数据:
df
是 :
Number_of_account Value
123 100
456 300
789 400
910 100
674 250
并且table_2
是:
Variable Number_of_account
"a" 123,456,910
"b" 789,674
首先,我将从 table2 创建一个查找表:
lookup_table = pd.concat([pd.Series(row['Variable'], row['Number_of_account'].split(','))
for _, row in table_2.iterrows()]).reset_index()
lookup_table.columns = ["Number_of_account", "variable"]
lookup_table.Number_of_account = pd.to_numeric(lookup_table.Number_of_account)
结果是:
Number_of_account variable
0 123 a
1 456 a
2 910 a
3 789 b
4 674 b
然后,我将主数据框 ( df
) 与查找表合并,并用于groupby
计算值的总和。
df = pd.merge(df, lookup_table, on="Number_of_account")
df.groupby("variable")["Value"].sum()
结果是:
variable
a 500
b 650
推荐阅读
- javascript - 在监听事件外的时间获取事件内的变量
- javascript - 如何在运行时获取所有控制台消息以登录 Cordova iOS?
- php - 如何在android文本视图上查看php脚本的结果
- itext - 使用 itextsharp 删除 pdf 文档中的图像
- collation - 如果在mysql中出现非法混合排序(utf8_bin,none)和(utf8_bin,none)错误,如何更新edmx
- recursion - 子程序调用的参数“n-1”给出了语法错误
- c# - 无法读取 .NET Core API 项目中的应用设置
- gcc - Linker fails in sandbox when running through Bazel but works when sandboxed command is executed from the command line
- javascript - 如何通过由ng-repeat在angularjs中动态创建的id获取元素
- featuretools - 如何在特征工具中获取列名列表