Skip to main content
 首页 » 编程设计

python之将列表作为索引传递给 Pandas 系列

2024年09月07日11daizhj

我可以将列表作为索引传递给 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 

为聚合转换为 float

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 

现在我想将我的 top buyer_codes 传递到我的 zz sereis 以仅获取与这些买家对应的交易数据。

我该怎么做?我在这里可能走错了路,但请帮助我。

请您参考如下方法:

我认为你需要:

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]