【问题标题】:python: Create a multiindex pandas DF based on condition of column namespython:根据列名条件创建多索引熊猫DF
【发布时间】:2022-12-06 21:21:21
【问题描述】:

我有一个数据框如下:

arrays = [np.array(["berlin", "berlin", "paris", "paris", "rome", "rome", "seville", "seville"]),
          np.array(["one", "two", "one", "two", "one", "two", "one", "two"])]
df = pd.DataFrame(np.random.randn(8, 4), index=arrays, columns = ['mike','ana','manu','analia'])

它在行中有一个多索引。 我想将该 DF 转换为另一个在列中也有 multindex 的 DF。

该功能可以概括为:

def sortit(colname):
    if colname.startswith('m'):
        return 'm'
    elif colname.startswith('m'): 
        return 'a'

预期输出如下:

arrays = [np.array(["berlin", "berlin", "paris", "paris", "rome", "rome", "seville", "seville"]),
          np.array(["one", "two", "one", "two", "one", "two", "one", "two"])]
tuples_i = list(zip(*arrays))
index_rows = pd.MultiIndex.from_tuples(tuples_i, names=["city", "number"])
arrays2 = [np.array(["m","m", "a","a"]),
          np.array(['mike','manu','ana','analia'])]
tuples_c = list(zip(*arrays2))
print(tuples)
index_columns = pd.MultiIndex.from_tuples(tuples_c, names=["department", "name"])
df = pd.DataFrame(np.random.randn(8, 4), index=index_rows, columns = index_columns)

df

两个重要的注意事项。

我的起点是在行中具有多索引而在列中具有非多索引的数据框。我无法改变这一点。

这里说明每个名称(列名)属于哪个多索引的方法是一个简单的方法,例如,实际情况是该函数更加复杂和耗时,这就是为什么我想创建一次多级列索引以便以后更快地进行查询。

【问题讨论】:

    标签: python pandas multi-index


    【解决方案1】:

    您可以使用MultiIndex.from_arrays 制作一个新的 MultiIndex:

    idx = pd.MultiIndex.from_arrays([df.columns.str.extract('(.)', expand=False),
                                     df.columns],
                                    names=['department', 'name'])
    
    df.columns = idx
    
    print(df.sort_index(level=0, axis=1))
    

    输出:

    department          a                   m          
    name              ana    analia      manu      mike
    berlin  one  0.465270 -0.549246  0.931020  0.027496
            two -2.156006 -2.053703  0.162281  0.741966
    paris   one  0.084072  1.729949  1.366554  0.402933
            two  1.157244  1.762093 -1.808943 -1.737110
    rome    one -0.009257 -0.457297 -0.479836 -2.483149
            two -0.593379 -0.012763 -1.491018 -0.439712
    seville one -1.118433  0.029189 -0.805858 -0.342481
            two -0.389120 -0.390189 -1.260496 -0.010572
    

    【讨论】:

      【解决方案2】:

      代码

      您可以通过制作元组轻松制作多索引

      (df.set_axis(df.columns.map(lambda x: (x[0], x)), axis=1)
       .rename_axis(['department', 'name'], axis=1))
      

      输出:

      department  m       a       m       a
      name        mike    ana     manu    analia
      berlin  one 0.6     -0.0    2.9     1.3
              two 1.3     0.4     0.0     -3.0
      paris   one -0.5    -0.8    0.4     0.0
              two -0.6    -1.0    0.5     0.3
      rome    one -1.5    0.2     -0.0    1.4
              two -1.5    -1.9    0.0     -0.0
      seville one -1.3    1.3     0.7     0.5
              two -0.2    -0.2    -0.7    0.4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-12
        • 1970-01-01
        • 2020-11-21
        • 2016-09-15
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        • 2016-06-16
        相关资源
        最近更新 更多