【问题标题】:pandas groupby multiple columns did not sort values by defaultpandas groupby 多列默认情况下不对值进行排序
【发布时间】:2019-07-10 09:55:14
【问题描述】:

我有以下df

code      pct         year_month
10        6.6156      201905
10        6.0868      201905
10        5.8975      201905
10        11.2195     201905
10        11.1404     201905 

我喜欢做以下事情

df2 = df.sort_values('pct', ascending=False)
df2['pct'].cumsum().le(20).mean()
0.2

groupby 的方式,

df.groupby(['year_month', 'code'])['pct'].apply(lambda x: x.cumsum().le(20).mean())

但结果不一样,

year_month  code
201905      BR10    0.6

我认为groupby 默认情况下应该按降序对pct 进行排序,但似乎不是,所以我想知道如何在每个year_monthcode 组中对pct 进行排序,然后再执行@ 987654332@;

【问题讨论】:

  • 它给了我同样的结果。你知道你是在对一系列布尔值取平均值吗?
  • @yatu 我正在使用 pandas 0.22,你的版本是什么?
  • 我的比较新。确保您使用的是相同的数据
  • @yatu 你能告诉我你的代码吗?
  • 和你的一样...

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

您的代码不同,对于相同的输出需要按前 2 列排序 - ['year_month','code'] 或使用此示例数据省略它(如果已排序):

print (df['pct'].cumsum().le(20).mean())
0.6

df2 = df.sort_values(['year_month','code'], ascending=False)
print (df2['pct'].cumsum().le(20).mean())
0.6

在 groupby 中对 groupby 中的值进行排序 - 这里是 ['year_month', 'code'],而不是 pct

df = df.groupby(['year_month', 'code'])['pct'].apply(lambda x: x.cumsum().le(20).mean())
print (df)
year_month  code
201905      10      0.6
Name: pct, dtype: float64

因此,对于相同的输出排序,此处按pct 列以及如果有必要防止按'year_month', 'code'] 排序,则添加sort=False

df2 = df.sort_values('pct', ascending=False)
print (df2['pct'].cumsum().le(20).mean())
0.2

df = (df.sort_values(['pct'], ascending=False)
        .groupby(['year_month', 'code'], sort=False)['pct']
        .apply(lambda x: x.cumsum().le(20).mean()))
print (df)
year_month  code
201905      10      0.2
Name: pct, dtype: float64

【讨论】:

    猜你喜欢
    • 2017-10-14
    • 2021-02-15
    • 2020-06-19
    • 2015-08-22
    • 1970-01-01
    • 2021-08-27
    • 2022-07-29
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多