gpt4 book ai didi

python-3.x - 在 groupby 中应用 pandas cut

转载 作者:行者123 更新时间:2023-12-05 05:21:46 25 4
gpt4 key购买 nike

我尝试在基于一列 (A) 的 DataFrame 中创建分箱 (A_bin),然后在每个原始分箱中基于另一列 (B) 创建唯一分箱 (B_bin)。

df = pd.DataFrame({'A': [4.5, 5.1, 5.9, 6.3, 6.7, 7.5, 7.9, 8.5, 8.9, 9.3, 9.9, 10.3, 10.9, 11.1, 11.3, 11.9],
'B': [3.2, 2.7, 2.2, 3.3, 2.1, 1.8, 1.4, 1.0, 1.8,2.4, 1.2, 0.8, 1.4, 0.6, 0, -0.4]})
df['A_bin'] = pd.cut(df['A'], bins=3)
df['B_bin'] = df.groupby('A_bin')['B'].transform(lambda x: pd.cut(x, bins=2))

这导致:

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-341-5742137b7574> in <module>()
2 'B': [3.2, 2.7, 2.2, 3.3, 2.1, 1.8, 1.4, 1.0, 1.8,2.4, 1.2, 0.8, 1.4, 0.6, 0, -0.4]})
3 df['A_bin'] = pd.cut(df['A'], bins=3)
----> 4 df['B_bin'] = df.groupby('A_bin')['B'].transform(lambda x: pd.cut(x, bins=2))

C:\Users\ddecker1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\groupby.py in transform(self, func, *args, **kwargs)
2761
2762 indexer = self._get_index(name)
-> 2763 result[indexer] = res
2764
2765 result = _possibly_downcast_to_dtype(result, dtype)

ValueError: could not convert string to float: '(2.0988, 2.7]'

看起来它正在尝试做正确的事情,但我不确定它为什么要尝试将字符串更改为 float 。

最佳答案

这是一种魔法:

df.groupby('A_bin')[['B']].transform(lambda x: pd.cut(x, bins=2))

关于python-3.x - 在 groupby 中应用 pandas cut,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42265471/

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