【问题标题】:How to shuffle the outer index randomly but the order the inner index in ascending order in a multi index dataframe如何随机打乱外部索引,但在多索引数据帧中按升序排列内部索引
【发布时间】:2021-10-03 09:46:23
【问题描述】:

以下代码生成示例数据框:

fruits=pd.DataFrame()
fruits['month']=['jan','feb','feb','march','jan','april','april','june','march','march','june','april']
fruits['fruit']=['apple','orange','pear','orange','apple','pear','cherry','pear','orange','cherry','apple','cherry']
ind_mnth=fruits['month'].values
ind_fruit=fruits['fruit'].values
fruits['price']=[30,20,40,25,30 ,45,60,45,25,55,37,60]
fruits_grp = fruits.set_index([ind_mnth, ind_fruit],drop=False)

如何在这个多索引数据框中随机打乱外部索引和升序的内部索引?

【问题讨论】:

  • sofruit 列依赖索引进行排序?
  • 是的,水果列取决于月份。

标签: pandas dataframe multi-index shuffle


【解决方案1】:

你可以试试这样的:

mnths = fruits.drop_duplicates(subset=['month']).sample(frac=1).reset_index().month.unique()
fruits.groupby(['month','fruit'])['price'].sum().loc[mnths]

首先您选择数据框中月份的随机排序,然后按月份和水果分组,这将按字母顺序排序,然后使用随机排序的月份列表进行索引

【讨论】:

  • 价格正在求和/相加。情况不应该如此。
  • 只有当月份和水果组合重复时才会相加。假设没有重复的行,这将不是问题
  • 假设数据集中有重复的月份和水果行,价格不求和
猜你喜欢
  • 2021-09-29
  • 2019-07-29
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2021-04-12
  • 2018-08-25
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多