Pandas将多索引列与同一行索引连接起来

2024-09-21 00:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想连接NumPy计算的多维输出,该输出在维度上与输入的形状相匹配(关于行和相应的选定列)。 但是它失败了:NotImplementedError: Can only union MultiIndex with MultiIndex or Index of tuples, try mi.to_flat_index().union(other) instead

我不想先把指数展平——那么有没有其他办法让它发挥作用呢

import pandas as pd
from pandas import Timestamp

df = pd.DataFrame({('metrik_0', Timestamp('2020-01-01 00:00:00')): {(1, 1): 2.5393693602911447, (1, 5): 4.316896324314225, (1, 6): 4.271001191238499, (1, 9): 2.8712588011247377, (1, 11): 4.0458495954752545}, ('metrik_0', Timestamp('2020-01-01 01:00:00')): {(1, 1): 4.02779063729038, (1, 5): 3.3849606155101224, (1, 6): 4.284114856052976, (1, 9): 3.980919941298365, (1, 11): 5.042488191587525}, ('metrik_0', Timestamp('2020-01-01 02:00:00')): {(1, 1): 2.374592085569529, (1, 5): 3.3405503781564487, (1, 6): 3.4049690284720366, (1, 9): 3.892686173978996, (1, 11): 2.1876998087043127}})

def compute_return_columns_to_df(df, colums_to_process,axis=0):
    method = 'compute_result'
    renamed_base_levels = map(lambda x: f'{x}_{method}', colums_to_process.get_level_values(0).unique())
    renamed_columns = colums_to_process.set_levels(renamed_base_levels, level=0)

    #####
    # perform calculation in numpy here
    # for the sake of simplicity (and as the actual computation is irrelevant - it is omitted in this minimal example)
    result = df[colums_to_process].values
    #####
    
    result = pd.DataFrame(result, columns=renamed_columns)
    display(result)    
    return pd.concat([df, result], axis=1) # fails with: NotImplementedError: Can only union MultiIndex with MultiIndex or Index of tuples, try mi.to_flat_index().union(other) instead.

# I do not want to flatten the indices first - so is there another way to get it to work?

compute_return_columns_to_df(df[df.columns[0:3]].head(), df.columns[0:2])

Tags: columnsoftodfwithresultprocesstimestamp
1条回答
网友
1楼 · 发布于 2024-09-21 00:32:39

代码失败的原因是:

result = df[colums_to_process].values
result = pd.DataFrame(result, columns=renamed_columns)

请注意,结果具有:

  • 顶级索引级别重命名为的列名 metrik_0_compute_result(到目前为止还可以)
  • 但是行索引是默认的单级索引, 由连续的数字组成

然后,当您连接dfresult时,熊猫尝试 对齐行索引上的两个源数据帧,但它们不兼容 (df有一个多指数,而result有一个“普通”指数)

将这部分代码更改为:

result = df[colums_to_process]
result.columns = renamed_columns

这样,结果保持原始指数,concat增加no 例外

另一个注释:您的函数包含参数,它是 从未使用过。考虑删除它。

另一种可能的方法

由于result有一个默认(单级)索引,因此您可以离开 代码的前一部分保持原样,但在加入之前重置df中的索引:

return pd.concat([df.reset_index(drop=True), result], axis=1)

通过这种方式,两个数据帧具有相同的索引,并且可以连接 他们也是

相关问题 更多 >

    热门问题