【问题标题】:Hierarchical indexing of Panda's dataframe using an n-d numpy array for indices使用 n-d numpy 数组作为索引对 Panda 的数据帧进行分层索引
【发布时间】:2021-01-07 12:21:13
【问题描述】:

我需要将 csv 文件中的参数数据读入 DataFrame 以进行统计分析。我想使用分层索引。我有 10 组参数,共有 70 种变化。 excel 表示的示例截图:

我尝试使用 n-d nparray 构建 df 以避免手动定义元组,但在使用数组、from_product、每个参数合并多个数据帧等之间迷路了:

params = np.array([[['Baseline'], ['orig']]
                       , [['Threshold'], ['Thresh-2', 'Thresh+2', 'Thresh_marg', 'Thresh_cort']]
                       , [['Marker'], ['MHx-2', 'MHx+2', 'MHz-2', 'MHz+2', 'MTx-2', 'MTx+2', 'MTz-2', 'MTz+2', 'MSx-2', 'MSx+2', 'MSz-2', 'MSz+2']]])

rows = []
df = []
paramLen = 0
paramdf = pd.DataFrame()
for i in range(len(params)):
    paramLen += len(params[i][1])
    rows.append(pd.MultiIndex.from_product(params[i]))
    df.append(pd.DataFrame(np.zeros(len(params[i][1])), index = rows[i]))
    paramdf = pd.concat([paramdf, df[i]])

有没有办法直接使用n-d数组进行索引?

【问题讨论】:

    标签: pandas numpy dataframe multi-index hierarchical


    【解决方案1】:

    目标序列不是多索引结构,所以据我所知没有办法直接展开。我使用您的方法将索引存储在两个列表中,并在最后创建了一个多索引。我没有以令人信服的方式回答这个问题,但我已经回答了另一种方式供您参考。

    import itertools
    idx1 = []
    idx2 = []
    for i in params:
        d = pd.MultiIndex.from_product(i)
        idx1.append(d.get_level_values(0).tolist())
        idx2.append(d.get_level_values(1).tolist())
    idx1 = list(itertools.chain.from_iterable(idx1))
    idx2 = list(itertools.chain.from_iterable(idx2))
    
    df = pd.MultiIndex.from_arrays([idx1, idx2], names=('Parameter','Value'))
    df
    MultiIndex([( 'Baseline',        'orig'),
                ('Threshold',    'Thresh-2'),
                ('Threshold',    'Thresh+2'),
                ('Threshold', 'Thresh_marg'),
                ('Threshold', 'Thresh_cort'),
                (   'Marker',       'MHx-2'),
                (   'Marker',       'MHx+2'),
                (   'Marker',       'MHz-2'),
                (   'Marker',       'MHz+2'),
                (   'Marker',       'MTx-2'),
                (   'Marker',       'MTx+2'),
                (   'Marker',       'MTz-2'),
                (   'Marker',       'MTz+2'),
                (   'Marker',       'MSx-2'),
                (   'Marker',       'MSx+2'),
                (   'Marker',       'MSz-2'),
                (   'Marker',       'MSz+2')],
               names=['Parameter', 'Value'])
    

    【讨论】:

      猜你喜欢
      • 2016-05-05
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 2018-05-02
      • 2020-03-29
      相关资源
      最近更新 更多