python - 为什么在对 df 中的几列进行分组后使用 df_grouped.loc[] 进行切片时出现错误?
问题描述
我是 SAS 用户。在 Python 中进行一些数据操作
isc_summary_sales=isc.groupby(['country','sales_channel','item_type'],as_index=False).aggregate({'order_id':['count'],'units_sold':['sum'],'unit_cost':['mean'],'unit_price':['mean'],'total_cost':['sum'])
上面的代码工作得很好,但是在尝试切片时,可以说
isc_summary_sales.loc[:,'country':'total_cost']
我收到一个错误
UnsortedIndexError: 'Key length (1) was greater than MultiIndex lexsort depth (0)'
但是,isc_summary_sales.iloc[:,0:7]
它可以正常工作。
我不明白这是什么意思。为什么会发生?
解决方案
它引发该错误的原因是因为在您聚合后,您的列有 2 级索引。
例如
import pandas as pd
df = pd.DataFrame({"a":[1, 1, 1, 2, 3, 2], "b":[1, 1, 3, 1, 2, 4], "c":[1, 2, 3, 1, 2, 4], "d":[1, 2, 3, 1, 2, 4]})
df_summary = df.groupby(["a", "b"], as_index=False).aggregate({"c":["mean", "sum"], "d":['sum']})
print(df_summary)
a b c d
mean sum sum
0 1 1 1.5 3 3
1 1 3 3.0 3 3
2 2 1 1.0 1 1
3 2 4 4.0 4 4
4 3 2 2.0 2 2
正如您现在看到的,您不再拥有简单的列“a”、“b”、“c”和“d”,而是拥有多级列。似乎方法“loc”要求我们的 DataFrame 是词法排序的,当我们聚合原始 DataFrame 时,我们创建了不再排序的新列。但是,我们可以使用以下方法再次对它们进行排序:
df_summary = df_summary.sortlevel(0, axis=1)
# And now this works
print(df_summary.loc[:, "b" : "d"])
b c d
mean sum sum
0 1 1.5 3 3
1 3 3.0 3 3
2 1 1.0 1 1
3 4 4.0 4 4
4 2 2.0 2 2
您可能还希望将列减少一级。我可以这样做:
df_summary.columns = ['_'.join(col[0] if col[1] == '' else col) for col in df_summary.columns]
# Which makes my DataFrame look like this
print(df_summary)
a b c_mean c_sum d_sum
0 1 1 1.5 3 3
1 1 3 3.0 3 3
2 2 1 1.0 1 1
3 2 4 4.0 4 4
4 3 2 2.0 2 2
更多关于多级索引的信息可以在这里找到:https ://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html
推荐阅读
- azure - 将 arm 参数传递给 Microsoft.VirtualMachineImages/imageTemplates 模板的 powershell 自定义部分
- java - UUID 问题,程序抛出 NullPointerException
- python - 以列表格式访问气流变量
- django - Django 应用程序 mod_wsgi 与 apache 错误
- google-analytics - 如何从 facebook 实时检索分析数据?
- oracle - REGEXP_LIKE 搜索多个单词忽略顺序
- php - 多种语言 PHP
- java - 通过持久属性的反射访问字段 [private int ...] 时出错
- angular - 如何安装内部角度库
- c++ - 如何让两段代码同时运行