gpt4 book ai didi

python - Pandas groupby 并获取两列

转载 作者:行者123 更新时间:2023-12-01 01:00:08 26 4
gpt4 key购买 nike

这是数据:作为字典

{'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 进行分组,并按 marketcap 获取 nlargest(2) 以及相应的代码

除了显示股票代码外,这可以完成所有操作,并且我无法market_cap 上的原始 df 合并,因为多个代码可以具有相同的市值

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_cap, ticker

最佳答案

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com