pandas - TypeError : Series. name must be a hashable type

标签 pandas pandas-groupby

    df = pd.DataFrame(
{
    "Index1": ["A", "A", "B", "B", "C"],
    "Index2": ["a", "b", "a", "c", "a"],
    "Param1": [1, 3, 1, 4, 2],
    "Param2": [2, 4, 3, 3, 4],
})

我想尝试 df.groupby(["Index1","Index2"])["Param1","Param2"].apply(lambda x:x['Param1']/x['Param2 ']),但得到这样的错误信息:TypeError: Series.name must be a hashable type, 我该如何解决,谢谢您的帮助。

我想生成如下数据 enter image description here

Index2  Index1  a   b   c
0   A   0.50    0.75    nan
1   B   0.33    nan 1.33
2   C   0.50    nan nan

这种格式是我使用的 df.assign(dis=lambda x:x.Param1/x.Param2).groupby(['Index1','Index2'])['dis'].apply(float ).unstack().reset_index() generate,我想知道.apply(float)的方式是否很危险

最佳答案

我觉得groupby这里没必要,只分列:

df['new'] = df['Param1']/df['Param2']
print (df)
  Index1 Index2  Param1  Param2       new
0      A      a       1       2  0.500000
1      A      b       3       4  0.750000
2      B      a       1       3  0.333333
3      B      c       4       3  1.333333
4      C      a       2       4  0.500000

然后使用DataFrame.pivot :

df = df.pivot('Index1','Index2','new')
print (df)
Index2         a     b         c
Index1                          
A       0.500000  0.75       NaN
B       0.333333   NaN  1.333333
C       0.500000   NaN       NaN

但是您的解决方案可以通过 Series.to_frame 实现:

df1 = (df.groupby(["Index1","Index2"])["Param1","Param2"]
         .apply(lambda x:(x['Param1']/x['Param2']).to_frame('new')))
print (df1)
        new
0  0.500000
1  0.750000
2  0.333333
3  1.333333
4  0.500000

关于pandas - TypeError : Series. name must be a hashable type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59388752/

相关文章:

python - 找到 Pandas 时间序列之间的相关性

python - Pandas - 将列名添加到 groupby 的结果中

python - Pandas - Groupby + Shift 未按预期工作

python - 转换数据框中(pandas/Python)中的系列,其中列是系列的级别

python - 使用 GroupBy 从长格式到宽格式

python - pandas 中具有多索引的 groupby 的平均值

python - 如何使用 pandas 根据唯一天数删除记录?

python - 为什么引用串联的 Pandas 数据框会返回多个条目?

python - 使用 one-hot 编码结果按日期、类别和客户对客户订单进行分组

python - 在 Pandas 中,根据不同模式选择多列的惯用方式是什么?