熊猫groupby并获得两列

凯南

这是数据:作为命令

{'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

我想GROUPBYdatebin并获得nlargest(2)通过marketcap与相应的沿ticker

这会执行所有操作,除了向我显示股票代码,而且由于多个可以具有相同的market_cap无法与原始df合并market_captickers

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']和column market_capticker

ky

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章