我是 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
关于python - 为什么在对 df 中的几列进行分组后使用 df_grouped.loc[ ] 进行切片时会出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59814240/