将List传递给pandas系列作为索引

时间:2018-01-09 11:08:14

标签: python pandas dataframe pandas-groupby

我可以将列表作为索引传递给pandas系列吗?

我有以下数据框:

d = {'no': ['1','2','3','4','5','6','7','8','9'], 'buyer_code': ['Buy1', 'Buy2', 'Buy3', 'Buy1', 'Buy2', 'Buy2', 'Buy2', 'Buy1', 'Buy3'], 'dollar_amount': ['200.25', '350.00', '120.00', '400.50', '1231.25', '700.00', '350.00', '200.25', '2340.00'], 'date': ['22-01-2010','14-03-2010','17-06-2010','13-04-2011','17-05-2011','28-01-2012','23-07-2012','25-10-2012','25-12-2012']}
df = pd.DataFrame(data=d)
df

    buyer_code  date        dollar_amount   no
0   Buy1        22-01-2010  200.25          1
1   Buy2        14-03-2010  350.00          2
2   Buy3        17-06-2010  120.00          3
3   Buy1        13-04-2011  400.50          4
4   Buy2        17-05-2011  1231.25         5
5   Buy2        28-01-2012  700.00          6
6   Buy2        23-07-2012  350.00          7
7   Buy1        25-10-2012  200.25          8
8   Buy3        25-12-2012  2340.00         9

转换为浮动以进行汇总

pd.options.display.float_format = '{:,.4f}'.format
df['dollar_amount'] = df['dollar_amount'].astype(float)

按频率和美元获取最重要的买家:

注意:在这里,我只获得前2名买家。在实际例子中,我可能需要获得最多40位买家。

xx = df.groupby('buyer_code').agg({'dollar_amount' : 'mean', 'no' : 'size'})
xx['frqAmnt'] = xx['no'].values * xx['dollar_amount'].values
xx = xx['frqAmnt'].nlargest(2)
xx

buyer_code
Buy2       2,631.2500
Buy3       2,460.0000
Name: frqAmnt, dtype: float64

对买家及其购买日期进行分组:

zz = df.groupby(['buyer_code'])['date'].value_counts().groupby('buyer_code').head(all)
zz

buyer_code  date      
Buy1        2010-01-22    1
            2011-04-13    1
            2012-10-25    1
Buy2        2010-03-14    1
            2011-05-17    1
            2012-01-28    1
            2012-07-23    1
Buy3        2010-06-17    1
            2012-12-25    1
Name: date, dtype: int64

现在我想将我的顶级buyer_codes传递给我的zz sereis,以便只获取与这些买家相对应的交易数据。

我该怎么办?我可能会走错路,但请帮助我。

1 个答案:

答案 0 :(得分:2)

我认为你需要:

a = zz[zz.index.get_level_values(0).isin(xx.index)]
print (a)
buyer_code  date      
Buy2        14-03-2010    1
            17-05-2011    1
            23-07-2012    1
            28-01-2012    1
Buy3        17-06-2010    1
            25-12-2012    1
Name: date, dtype: int64

对于订单需求reindex

a = zz[zz.index.get_level_values(0).isin(xx.index)].reindex(xx.index, level=0)

buyer_code所有日期:

b = a.reset_index(name='a').groupby('buyer_code')['date'].apply(list).reset_index()
print (b)
  buyer_code                                              date
0       Buy2  [14-03-2010, 17-05-2011, 23-07-2012, 28-01-2012]
1       Buy3                          [17-06-2010, 25-12-2012]