Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

python 3.x - applying pandas cut within a groupby

I'm trying to create bins (A_bin) within a DataFrame based on one column (A), and then create unique bins (B_bin) based on another column (B) within each of the original bins.

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)) 

This results in:

---------------------------------------------------------------------------
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:Usersddecker1AppDataLocalContinuumAnaconda3libsite-packagespandascoregroupby.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]'

It looks like it's trying to do the right thing, but I'm not sure why it's trying to change the the string to float.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's a kind of magic:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...