我的需求:比如
有1个2021年12月以来的A股股票的日交易记录(dataframe),有三列:股票代码:code,市值:mv,交易日期:date
,我想利用group 、rank等方法求出某只股票(比如:'000001')在每个交易日期中市值(mv)在所有股票中的排名(rank),怎么都没有思路。
请教了!
import pandas as pd
data = [[101, 236423, '2021-01'],
[101, 223387, '2021-02'],
[102, 397845, '2021-01'],
[102, 138257, '2021-02'],
[103, 83475, '2021-01'],
[103, 393475, '2021-02']]
df = pd.DataFrame(data=data, columns=['code', 'mv', 'date'])
print(df)
def f(series):
tmpDf = pd.merge(series,df,on ='date')
res = tmpDf.groupby(by='date').apply(lambda x: ((x['code_y'] !=x['code_x']) & (x['mv_y'] > x['mv_x'])).sum() + 1).reset_index(name='count')
return res
df = df.groupby('code').apply(f)
print(df)
'''
--result
code mv date
0 101 236423 2021-01
1 101 223387 2021-02
2 102 397845 2021-01
3 102 138257 2021-02
4 103 83475 2021-01
5 103 393475 2021-02
date count
code
101 0 2021-01 2
1 2021-02 2
102 0 2021-01 1
1 2021-02 3
103 0 2021-01 3
1 2021-02 1
'''