将 Pandas 系列转换为格式良好的数据框

Converting a Pandas Series to a Well-Formed Dataframe

我有一个 groupby 对象:

g = dfchurn.groupby('ID')['isconfirm'].value_counts().groupby(level=0).apply(lambda x: x / float(x.sum())) 
type(g) 
Out[230]: pandas.core.series.Series
g.head(5)
Out[226]: 
ID         isconfirm
0000       0            0.985981
           1            0.014019
0064       0            0.996448
           1            0.003552
0080       0            0.997137   

我的目标是让前 100 个 ID 按降序(最右边的列)排序,其中 isconfirm=0。
为此,我考虑过使用命名良好的列来创建一个漂亮的数据框,这样我就可以在 isconfirm=0 时根据比率查询顶级 ID。

我试过了,例如,

gdf = g.to_frame() 
gdf.unstack(level=1) 
gdf.head(5) 

           isconfirm          
isconfirm         0         1
ID                    
0000       0.985981  0.014019
0064       0.996448  0.003552

gdf.columns
Out[227]: Index([u'isconfirm'], dtype='object')

这并没有导致任何结果。必须有一种干净简洁的方式来做到这一点。

我在相关问题中找到了提示:

gdf.unstack(level=1) 
gdf  = gdf.add_suffix('_ratio').reset_index()  # KEY STEP

gdf.columns   #  friendly columns now  
Index([u'ID', u'isconfirm', u'isconfirm_ratio'], dtype='object')

gdf[gdf['isconfirm_ratio'] > 0.999]   # e.g. a filter like this works now or a sort

您可以 select 所有 isconfirm 为 0 的行,使用 g.loc:

In [90]: g.loc[:, 0]
Out[90]: 
ID
0    0.827957
1    0.911111
2    0.944954
3    0.884956
4    0.931373
5    0.869048
6    0.941176
7    0.884615
8    0.901961
9    0.930693
Name: isconfirm, dtype: float64

[:, 0]中的0指的是二级索引中的值。 因此,您可以使用以下方法找到与前 100 个值相对应的 IDs:

In [93]: g.loc[:, 0].sort_values(ascending=False).head(100)
Out[93]: 
ID
2    0.944954
6    0.941176
4    0.931373
9    0.930693
1    0.911111
8    0.901961
3    0.884956
7    0.884615
5    0.869048
0    0.827957
Name: isconfirm, dtype: float64

In [94]: g.loc[:, 0].sort_values(ascending=False).head(100).index
Out[94]: Int64Index([2, 6, 4, 9, 1, 8, 3, 7, 5, 0], dtype='int64', name='ID')

为了产生上面的结果,我这样定义 g

import numpy as np
import pandas as pd
np.random.seed(2017)

N = 1000
dfchurn = pd.DataFrame({'ID':np.random.randint(10, size=N),
                        'isconfirm': np.random.choice(2, p=[0.9, 0.1], size=N)})
g = dfchurn.groupby('ID')['isconfirm'].value_counts().groupby(level=0).apply(lambda x: x / float(x.sum()))