gpt4 book ai didi

python - Pandas `transform(set)` 引发异常

转载 作者:行者123 更新时间:2023-12-04 00:01:58 25 4
gpt4 key购买 nike

我正在尝试通过 set 进行转换,但出现异常。变换适用于“sum”和许多其他聚合函数,但不适用于 setlist

>>> import pandas as pd
>>> df = pd.DataFrame({"a":[1,2,1,], "b":[1,1,2]})
>>> df
a b
0 1 1
1 2 1
2 1 2
>>> df.groupby("a").b.transform(set)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/avloss/conda/lib/python3.7/site-packages/pandas/core/groupby/generic.py", line 1032, in transform
s = klass(res, indexer)
File "/Users/avloss/conda/lib/python3.7/site-packages/pandas/core/series.py", line 282, in __init__
"{0!r} type is unordered" "".format(data.__class__.__name__)
TypeError: 'set' type is unordered

我所期待的是:

   a      b   
0 1 {1, 2}
1 2 {1}
2 1 {1, 2}

最佳答案

我能想到的最简单的方法是 aggregate 作为 set 并将其映射回来

df['new_col'] = df['a'].map(df.groupby('a')['b'].agg(set))
print(df)

   a  b new_col
0 1 1 {1, 2}
1 2 1 {1}
2 1 2 {1, 2}

关于python - Pandas `transform(set)` 引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59990361/

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