为了使用groupby和qcut,Pandas会丢弃唯一的行

问题描述 投票:2回答:1

我如何放弃独特?它干扰了groupby和qcut。

df0 = psql.read_frame(sql_query,conn)
df = df0.sort(['industry','C'], ascending=[False,True] )

这是我的数据帧:

    id                    industry     C
5   28              other industry  0.22
9   32          Specialty Eateries  0.60
10  33                 Restaurants  0.84
1   22  Processed & Packaged Goods  0.07
0   21  Processed & Packaged Goods  0.14
8   31  Processed & Packaged Goods  0.43
11  34  Major Integrated Oil & Gas  0.07
14  37  Major Integrated Oil & Gas  0.50
15  38       Independent Oil & Gas  0.06
18  41       Independent Oil & Gas  0.06
19  42       Independent Oil & Gas  0.13
12  35       Independent Oil & Gas  0.43
16  39       Independent Oil & Gas  0.65
17  40       Independent Oil & Gas  0.91
13  36       Independent Oil & Gas  2.25
2   25    Food - Major Diversified  0.35
3   26     Beverages - Soft Drinks  0.54
4   27     Beverages - Soft Drinks  0.73
6   29         Beverages - Brewers  0.19
7   30         Beverages - Brewers  0.21

而且我使用了pandas and qcut的以下代码对“C”列进行排名,这对我来说很糟糕。

df['rank'] = df.groupby(['industry'])['C'].transform(lambda x: pd.qcut(x,5, labels=range(1,6)))

经过一番研究,qcut抛出错误的原因是因为行业专栏reference to erroranother ref to err的独特价值。

虽然,我仍然希望能够排名而不抛出唯一(唯一应该赋值1),如果可能的话。但是经过这么多尝试之后,我确信qcut无法处理独特的问题,所以我愿意为了让qcut乐于做其事而放弃独特。

但如果还有另一种方式,我很想知道。我非常感谢你的帮助。

python pandas group-by
1个回答
0
投票

以防任何人仍然想要这样做。你应该能够通过只选择重复项来做到这一点?

df = df[df['industry'].duplicated(keep=False)]
© www.soinside.com 2019 - 2024. All rights reserved.