我对Python还不太熟悉。我在SO上看到了一个关于Pandas和两个列的组合的问题:Pandas:按两个列的组合进行分组。不幸的是,这个被接受的答案在pandas版本
以下是被接受的答案:
0.23.4
中不再起作用。那篇文章的目的是找出组合变量,并为值创建一个字典。也就是说,group_by
应该忽略分组的顺序。以下是被接受的答案:
import pandas as pd
from collections import Counter
d = pd.DataFrame([('a','b',1), ('a','c', 2), ('b','a',3), ('b','a',3)],
columns=['x', 'y', 'score'])
d[['x', 'y']] = d[['x', 'y']].apply(sorted, axis=1)
x = d.groupby(['x', 'y']).agg(Counter)
print(x)
这里,...apply(sorted)
抛出下面的异常:
raise ValueError('Must have equal len keys and value ' ValueError: Must have equal len keys and value when setting with an iterable
这是我的 pandas 版本:
> pd.__version__
Out: '0.23.4'
在阅读完https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html后,以下是我尝试的内容:
d = pd.DataFrame([('a','b',1), ('a','c', 2), ('b','a',3), ('b','a',3)],
columns=['x', 'y', 'score'])
d=d.sort_values(by=['x','y'],axis=1).reset_index(drop=True)
x = d.groupby(['x', 'y']).agg(Counter)
print(x)
不幸的是,这也会抛出错误:
在_get_label_or_level_values中的1382行 报错:KeyError(key) KeyError: 'x'
期望输出:
score count
x y
a b {1: 1, 3: 2} 2
c {2: 1} 1
请问有人可以帮帮我吗?另外,如果您能指导如何计算score
列中keys()
的数量,并提供向量化解决方案,那将非常棒。
我正在使用Python 3.6.7
。
非常感谢。
pandas
指出:“broadcast: Deprecated since version 0.23.0: This argument will be removed in a future version, replaced by result_type=’broadcast’。” - watchtower