gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:58:01 28 4
gpt4 key购买 nike

    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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com