python - 为什么在对 df 中的几列进行分组后使用 df_grouped.loc[ ] 进行切片时会出现错误?

标签 python

我是 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/

相关文章:

python - Ruamel yaml 转储嵌套列表的格式

Python Selenium Webdriver : how to select more than one element using get_attribute

python - matplotlib 文档中的烛台示例中的 ImportError : `cannot import name quotes_historical_yahoo_ohlc`

python - 对数据帧中的列执行 str.split 会返回SettingWithCopyWarning

python - 将两个数据框与其中一列内的列表合并

python - 如何使 2 个列表框与相同的函数绑定(bind),而无需在选择另一个列表框时为两个列表框运行相同的函数两次?

python - 使用web3.py查询远程以太坊节点时出现间歇性 "Read time out"错误

python - 如何在python中做一个条件装饰器

python - Pandas DataFrame 到 Numpy 数组 ValueError

python - 如何使用正则表达式拆分列以将尾随大写字母移动到单独的列中?