熊猫groupby并获得两列

时间:2019-04-26 17:44:54

标签: python pandas dataframe datetime pandas-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'}}

DataFrame:

        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

除了向我显示股票代码,我不能与原始df合并外,它会做所有事情,因为多个market_cap可以具有相同的market_cap

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

理想的答案应该是MultiIndex ['date','bin']和列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 market_cap

1 个答案:

答案 0 :(得分:2)

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

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