python-3.x - groupby python 类型错误 : unorderable types: tuple() < str()

标签 python-3.x pandas

我最初在 python 2.7 中写了一些代码,但现在我切换到 python 3.5。 我想聚合来自几列的数字数据,并按其余列或至少一列进行分组。

这是我的初始数据框“testdf”:

testdf
     PROD_TAG   BRAND   Market         ('VAL', 'Per1')  ('VAL', 'Per2')
        P_1       A     Modern Trade         4.3           0.155
        P_2       A     Traditional Trade    5.7           0
        P_3       B     Modern Trade         10.0          11.2
        P_3       B     Traditional Trade    8.7           6.3
        P_4       C     Modern Trade         12.1          12.3
        P_5       D     Modern Trade         8.0           7.0

最后两列标题是元组(感谢 captain obvious)。 Per1和Per2代表各自的时期。

我想执行一行代码,它以前在 python 2.7 上运行过:

testdf=testdf.groupby(['BRAND'])[('VAL','P1'),('VAL','P2')].sum()

由于列标题和加注的元组类型,它不起作用:

TypeError: unorderable types: tuple() < str()

现在,如果我像这样重命名列标题:

testdf.columns=['PROD_TAG', 'BRAND', 'Market', 'VAL-P1', 'VAL-P2']

(删除元组)我将能够使用新的列名称执行同一行代码:

testdf1=testdf.groupby(['BRAND'])['VAL-P1','VAL-P2'].sum()

最后:

BRAND     ('VAL', 'Per1')   ('VAL', 'Per2')
  A            10.0              0.155
  B            18.7              17.5
  C            12.1              12.3
  D            8.0               7.0

这里最奇怪的是,如果我使用 .mean() 而不是 .sum()、min() 或 .max(),即使用元组。

任何人都可以解释一下如何在 python 3.5 上使用元组列名称进行此类聚合吗?

最佳答案

我认为你需要使用 groupby.agg并传递一个函数来聚合每个组的总和,如下所示:

df = pd.DataFrame({'PROD_TAG':["P_1", "P_2", "P_3", "P_3", "P_4", "P_5"],
                   'BRAND':["A", "A", "B", "B", "C", "D"],
                   'Market':["Modern Trade", "Traditional Trade",   \
                   "Modern Trade", "Traditional Trade", "Modern Trade", "Modern Trade"],
                   ('VAL','Per1'):[4.3, 5.7, 10.0, 8.7, 12.1, 8.0],
                   ('VAL','Per2'):[0.155, 0, 11.2, 6.3, 12.3, 7.0]})

type(df[('VAL','Per1')].name)
#<class 'tuple'>

df.groupby(['BRAND'])[('VAL','Per1'), ('VAL','Per2')].agg(lambda x: x.sum())

       (VAL, Per1)  (VAL, Per2)
BRAND                          
A             10.0        0.155
B             18.7       17.500
C             12.1       12.300
D              8.0        7.000

或者,不重置索引并转换石斑鱼列。因此,您可以消除由于列 [tuple/str] 的名称不匹配导致的 TypeError

df.groupby(['BRAND'], as_index=False)[('VAL','Per1'), ('VAL','Per2')].sum()

  BRAND  (VAL, Per1)  (VAL, Per2)
0     A         10.0        0.155
1     B         18.7       17.500
2     C         12.1       12.300
3     D          8.0        7.000

但是如果你renametuple 列转换为 string,您可以像以前一样继续操作而无需使用 agg 函数:

df.rename(index=str, columns={('VAL','Per1'): "('VAL','Per1')",      \
                              ('VAL','Per2'): "('VAL','Per2')"}, inplace=True)

type(df["('VAL','Per1')"].name)
#<class 'str'>

df.groupby(['BRAND'])["('VAL','Per1')","('VAL','Per2')"].sum()

       ('VAL','Per1')  ('VAL','Per2')
BRAND                                
A                10.0           0.155
B                18.7          17.500
C                12.1          12.300
D                 8.0           7.000

注意:Python 3.5

中测试

关于python-3.x - groupby python 类型错误 : unorderable types: tuple() < str(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39052266/

相关文章:

Python 3 类(class),在打印语句末尾的句点之前有额外空间问题

python - 通过 strip() 有效地使用元组

python - 查询 SQL Server 数据库时结果对象不返回行

python - 使用 Pandas groupby 迭代和修改数据框

python - 如何将 DataFrame 中的 K 个随机值附加到不重复的列表列表中?

python - 无法导入 numpy : AttributeError: type object 'numpy.ndarray' has no attribute '__array_function__'

python - dask dataframe.persist() 是否保留下一个查询的结果?

python - 将 Pandas 数据框转换为包含索引、数据和列的列表列表

python - 在django中下载和保存文档的问题

python - 如何在Python中填写插入语句的列名