这是数据:
作为命令

{'date': {2: Timestamp('2019-04-29 00:00:00'), 3: Timestamp('2019-04-29 00:00:00'), 4: Timestamp('2019-04-29 00:00:00'), 5: Timestamp('2019-04-29 00:00:00'), 6: Timestamp('2019-04-30 00:00:00'), 7: Timestamp('2019-04-30 00:00:00'), 8: Timestamp('2019-04-30 00:00:00'), 9: Timestamp('2019-04-30 00:00:00')}, 'tickers': {2: 'SOGO', 3: 'CHGG', 4: 'GOOG', 5: 'GOOGL', 6: 'ARLO', 7: 'MTLS', 8: 'MSTR', 9: 'CVLT'}, 'market_cap': {2: 2109999999.9999998, 3: 4520000000.0, 4: 873150000000.0, 5: 875970000000.0, 6: 293310000.0, 7: 890760000.0, 8: 1530000000.0, 9: 2830000000.0}, 'bin': {2: '1', 3: '0', 4: '0', 5: '0', 6: '0', 7: '1', 8: '0', 9: '1'}}


数据框:

        date        ticker  market_cap           bin
2     2019-04-29    SOGO  2.110000e+09            1
3     2019-04-29    CHGG  4.520000e+09            0
4     2019-04-29    GOOG  8.731500e+11            0
5     2019-04-29   GOOGL  8.759700e+11            0
6     2019-04-30    ARLO  2.933100e+08            0
7     2019-04-30    MTLS  8.907600e+08            1
8     2019-04-30    MSTR  1.530000e+09            0
9     2019-04-30    CVLT  2.830000e+09            1


我想对datebin进行分组,并通过nlargest(2)与相应的marketcap一起获得ticker

除了向我显示股票代码,我不能与market_cap上的原始df合并,因为它可以执行所有操作,因为多个tickers可以具有相同的market_cap

df.groupby(['expected_date', 'bin'])['market_cap'].nlargest(2)


2019-04-29     0           5    8.759700e+11
                           4    8.731500e+11
               1           2    2.110000e+09
2019-04-30     0           8    1.530000e+09
                           6    2.933100e+08
               1           9    2.830000e+09
                           7    8.907600e+08



理想的答案应该是MultiIndex ['date','bin']和列market_capticker

最佳答案

尝试使用(请根据提供的示例更改列名称):

df[df.groupby(['date', 'time'])['market_cap'].rank(method='dense',ascending=False)<=2]




        date tickers    market_cap time
2 2019-04-29    SOGO  2.110000e+09    1
4 2019-04-29    GOOG  8.731500e+11    0
5 2019-04-29   GOOGL  8.759700e+11    0
6 2019-04-30    ARLO  2.933100e+08    0
7 2019-04-30    MTLS  8.907600e+08    1
8 2019-04-30    MSTR  1.530000e+09    0
9 2019-04-30    CVLT  2.830000e+09    1

关于python - Pandas groupby并获得两列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55872643/

10-11 11:35