【问题标题】:Pandas, Future Warning: Indexing with multiple keysPandas,未来警告:使用多个键进行索引
【发布时间】:2020-07-14 21:45:48
【问题描述】:

当我将函数应用于 groupby 对象的多个列时,Pandas 会引发未来警告。它建议使用列表而不是元组作为索引。怎么办?

>>> df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
>>> df.groupby([0,1])[1,2].apply(sum)
<stdin>:1: FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.
     1  2
0 1      
1 2  2  3
4 5  5  6
7 8  8  9

【问题讨论】:

  • [[1, 2]]。 2 Brackets 是您进行 DataFrame 选择的方式(即使用列表进行选择)。我很惊讶 [1,2] 一直在工作。
  • 谢谢,你是对的!也许这应该引发 Keyerror。
  • [[1,2]].sum()。无需apply内置python的sum函数
  • 正确,但 sum 只是可视化我的问题的一个示例。
  • 决定是github.com/pandas-dev/pandas/issues/23566。为了保持 0.25 和 1.0 之间的兼容性,他们没有删除该功能,而是在 1.0 中添加了警告。可能会在下一个主要的弃用周期中删除。

标签: python pandas


【解决方案1】:

此警告是在 pandas 1.0.0 中引入的,位于 discussion on GitHub 之后。所以最好使用那里的建议:

df.groupby([0, 1])[[1, 2]].apply(sum)

也可以将切片操作移到最后,但效率不高:

df.groupby([0, 1]).apply(sum).loc[:, 1:]

感谢 @ALollz 和 @cmosig 提供帮助的 cmets。

【讨论】:

  • 您应该将@ALollz 的评论整合到您的答案中,而不仅仅是引用它。这就是为什么另一个答案会被赞成的原因,即使你很早就有了答案。您只需要解释为什么需要双括号 - 而 cmets 不属于答案。
【解决方案2】:

在 groupby 方法后使用双括号。 单括号用于输出 Pandas Series,双括号用于输出 Pandas DataFrame。

df.groupby([0,1])[[1,2]].apply(sum)

【讨论】:

  • 这应该是@Arne 回答下的评论/编辑。
【解决方案3】:

上面的例子有些琐碎。我正在尝试以更复杂的代码删除警告消息。如何转换下面的代码以使用列列表来消除警告?

# Standard imports
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

# Ensure plots are displayed inline
%matplotlib inline
#%matplotlib notebook

# Read in some data to show some real world exampled
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true")

# Examine the dataframe
df.head()

# Summarize the data by customer and get the top 10 customers. Also, clean up the column names for consistency

top_10 = (df.groupby('name')['ext price', 'quantity']
          .agg({'ext price': 'sum', 'quantity': 'count'})
          .sort_values(by='ext price', ascending=False))[:10].reset_index()

`C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead.
  """Entry point for launching an IPython kernel.`

# Output the top 10
top_10

我尝试了这段代码,但我确实出错了,而不仅仅是警告:

top_10 = (df.groupby('name')['ext price', 'quantity']
          .agg([['ext price', 'sum'], ['quantity', 'count']])
          .sort_values(by='ext price', ascending=False))[:10].reset_index()

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning:使用多个键进行索引(隐式转换为 元组键)将被弃用,请改用列表。 “““入口 启动 IPython 内核的要点。

----------------------------------- ---------------------------- TypeError Traceback(最近一次调用 最后)~\AppData\Local\Temp/ipykernel_3644/534927805.py 在 1 top_10 = (df.groupby('name')['ext price', 'quantity'] ----> 2 .agg([['ext price', 'sum'], ['quantity', 'count']]) 3 .sort_values(by='ext price', ascending=False))[:10].reset_index()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby\generic.py 汇总(自我,函数,引擎,engine_kwargs,*args,**kwargs) 940 返回 self.obj._constructor(结果,索引 = 索引,列 = 数据列) 941 --> 942 重新标记,函数,列,顺序 = 重构函数(函数,**kwargs) 第943章 第944章

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\aggregation.py 在reconstruct_func(func, **kwargs) 88 89 如果不重新标记: ---> 90 如果 isinstance(func, list) 和 len(func) > len(set(func)): 91 92 # GH 28426 如果使用了重复的函数名并且会引发错误

TypeError: unhashable type: 'list'

【讨论】:

  • 我想通了:top_10 = (df.groupby('name')['ext price', 'quantity'] .agg({'ext price': 'sum', 'quantity': 'count'}) .sort_values(by='ext price', ascending=False))[:10].reset_index()
猜你喜欢
  • 2021-12-13
  • 2023-03-11
  • 2014-09-28
  • 2018-11-22
  • 1970-01-01
  • 2019-12-25
  • 2019-07-26
  • 1970-01-01
  • 2017-08-19
相关资源
最近更新 更多