【问题标题】:How to shuffle the outer index randomly and inner index in a different random order in a multi index dataframe如何在多索引数据框中以不同的随机顺序随机打乱外部索引和内部索引
【发布时间】:2021-09-29 19:36:36
【问题描述】:

以下是生成示例数据框的一些代码:

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=fruits.index
ind_mnth=fruits['month'].values
fruits['price']=[30,20,40,25,30 ,45,60,45,25,55,37,60]
fruits_grp = fruits.set_index([ind_mnth, ind],drop=False)

如何在这个多索引数据帧中随机打乱外部索引和内部索引以不同的随机顺序?

【问题讨论】:

  • 你真的要去掉内索引和外索引之间的关联吗?
  • 不,我希望执行 2 级随机播放。首先打乱外部索引(月),然后在相同的外部索引(月)中打乱内部索引。
  • 请参考正在执行的类似任务,stackoverflow.com/questions/55054185/…,不同之处在于我想以随机顺序对外部索引和内部索引进行洗牌。
  • 您可以对数据框进行采样df.sample(frac=1)
  • 这能回答你的问题吗? Shuffle DataFrame rows

标签: pandas dataframe multi-index shuffle


【解决方案1】:

假设这个数据框以 MultiIndex 作为输入:

          month   fruit  price
jan   0     jan   apple     30
feb   1     feb  orange     20
      2     feb    pear     40
march 3   march  orange     25
jan   4     jan   apple     30
april 5   april    pear     45
      6   april  cherry     60
june  7    june    pear     45
march 8   march  orange     25
      9   march  cherry     55
june  10   june   apple     37
april 11  april  cherry     60

首先打乱整个 DataFrame,然后通过按随机顺序索引来重新组合月份:

np.random.seed(0)
idx0 = np.unique(fruits_grp.index.get_level_values(0))
np.random.shuffle(idx0)
fruits_grp.sample(frac=1).loc[idx0]

输出:

          month   fruit  price
jan   0     jan   apple     30
      4     jan   apple     30
april 6   april  cherry     60
      5   april    pear     45
      11  april  cherry     60
feb   1     feb  orange     20
      2     feb    pear     40
june  10   june   apple     37
      7    june    pear     45
march 8   march  orange     25
      9   march  cherry     55
      3   march  orange     25

【讨论】:

  • 一旦月份被洗牌,第二级洗牌只能在同一组月份中发生,换句话说,以四月为索引的行只能在它们之间洗牌,而不是任何其他月份
  • 好的,不清楚。它现在应该可以按预期工作了
  • 如何随机打乱外部索引,内部索引升序?
猜你喜欢
  • 2021-10-03
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多