current position:Home>Find a pandas (dataframe) grouping problem to find rank

Find a pandas (dataframe) grouping problem to find rank

2022-01-27 03:00:24 CSDN Q & A

My needs : such as
Yes 1 individual 2021 year 12 Since A Daily trading records of shares (dataframe), There are three columns : Stock code :code, Market value :mv, Transaction date :date
, I want to use group 、rank And other methods to find a stock ( such as :'000001') Market value on each trading date (mv) Ranking in all stocks (rank), I don't have any ideas .
Please ask !




Refer to the answer 1:
import pandas as pddata = [[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     date0   101  236423  2021-011   101  223387  2021-022   102  397845  2021-013   102  138257  2021-024   103   83475  2021-015   103  393475  2021-02           date  countcode                  101  0  2021-01      2     1  2021-02      2102  0  2021-01      1     1  2021-02      3103  0  2021-01      3     1  2021-02      1'''



Refer to the answer 2:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270300223800.html

Random recommended