gpt4 book ai didi

python - 过滤然后对多级索引数据框进行排序

转载 作者:行者123 更新时间:2023-11-28 18:33:27 24 4
gpt4 key购买 nike

我有一个包含两列(Col1 和 Col2)和一个多级索引(日期和符号)的 pandas Dataframe,如下所示:

                 Col1    Col2
Date Symbol
2015-12-01 AAA 0.45 0.53
BBB -1.02 -0.57
CCC -0.41 0.30
2015-11-02 AAA 0.59 -0.42
BBB -2.16 -0.77
CCC -1.02 1.09
2015-10-01 AAA -0.44 -0.88
BBB 0.52 0.27
CCC -1.76 0.63

复制此 Dataframe 的代码是:

    df = pd.DataFrame({'Date': ['2015-12-01']*3 + ['2015-11-02']*3 + ['2015-10-01']*3,
'Symbol': ['AAA','BBB','CCC']*3,
'Col1': 0.45,-1.02,-0.41,0.59,-2.16,-1.02,-0.44,0.52,-1.76],
'Col2': [0.53,-0.57,0.3,-0.42,-0.77,1.09,-0.88,0.27,0.63]},
).set_index(['Date', 'Symbol'])

在每个日期内,我尝试根据 Col1 中的最大值选择前 n 行(在本例中为 2),然后根据 Col2 中的值(最大 == 1,第二大)对这些行进行排名== 2 等)。将结果作为列添加到原始 Dataframe,最终的 Dataframe 应如下所示:

                 Col1   Col2    Rank
Date Symbol
2015-12-01 AAA 0.45 0.53 1
CCC -0.41 0.30 2
BBB -1.02 -0.57 NaN
2015-11-02 CCC -1.02 1.09 1
AAA 0.59 -0.42 2
BBB -2.16 -0.77 NaN
2015-10-01 BBB 0.52 0.27 1
AAA -0.44 -0.88 2
CCC -1.76 0.63 NaN

我尝试过使用 groupby 和 rank 函数,但我很难正确地建立索引。

例如,df.reset_index().groupby(['Date'])['Col1'].nlargest(2) 产生:

Date         
2015-10-01 7 0.52
6 -0.44
2015-11-02 3 0.59
5 -1.02
2015-12-01 0 0.45
2 -0.41

但我不知道如何排序并将结果放回 Dataframe。

最佳答案

您可以执行以下操作:

 df['largest'] = df.groupby(level='Date').apply(lambda x: x.Col1.nlargest(2)).reset_index(0, drop=True)
df['ranked'] = df.groupby(level='Date').apply(lambda x: x.dropna(subset=['largest']).Col2.rank(ascending=False)).reset_index(0, drop=True)

得到:

                   Col1  Col2  largest  ranked
Date Symbol
2015-12-01 AAA 0.45 0.53 0.45 1
BBB -1.02 -0.57 NaN NaN
CCC -0.41 0.30 -0.41 2
2015-11-02 AAA 0.59 -0.42 0.59 2
BBB -2.16 -0.77 NaN NaN
CCC -1.02 1.09 -1.02 1
2015-10-01 AAA -0.44 -0.88 -0.44 2
BBB 0.52 0.27 0.52 1
CCC -1.76 0.63 NaN NaN

关于python - 过滤然后对多级索引数据框进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34769639/

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