熊猫多索引数据框重命名轴/索引

时间:2020-11-12 17:37:31

标签: pandas dataframe multi-index

我有一个用于模拟Excel电子表格的mul​​tiindex数据框,其中每行有20个单元格,每个单元格内有3个我要跟踪的属性。

def build_matrix(self):
    all_data = pd.Dataframe()
    
    # create 30 rows of data to start
    for y in range(30):
        next_row = self.add_row_to_matrix()
        all_data = all_data.append(next_row, ignore_index=True)

    return all_data

def add_row_to_matrix(self):
    cell_numbers = []
    attribute_names = []
    attribute_values = []
    cell_attr_names = ["type_of_data", "start_time", "cell_number"]
    cell_default_vals = ["Unassigned", "NoDate", -1.00]

    # build a row of 20 cells
    for x in range(20):
        cell_num = "CELL_" + str(x + 1)
        for y in range(3):
            cell_numbers.append(cell_num)
        for z in range(3):
            attribute_names.append(cell_attr_names[z])
            attribute_values.append(cell_default_vals[z])

    row_of_data = [cell_numbers, attribute_names]
    col = pd.MultiIndex.from_arrays(row_of_data)

    data_df = pd.DataFrame([attribute_values], columns=col)
    return data_df

然后我执行一个过程来填充数据,如下所示:

            CELL_1             ...   CELL_20
       type_of_data start_time ... type_of_data start_time
    0  Unassigned   2020-11-10     Unassigned   2020-11-10
    1  MovingUp     2020-11-10     Stationary   2020-11-11
    2  Stationary   2020-11-11     MovingDown   2020-11-11

最终我可能不得不“转移”我要工作的数据

def shift_matrix(self, the_matrix):

    the_matrix[("CELL_1")] = the_matrix[("CELL_1")].shift(-1)

当数据移动时,值(以及“ CELL_#”)需要更改。更改“ cell_number”的值,就像使用“ loc”一样。

the_matrix.loc[:, ("CELL_1", "cell_number")] = some_value

但是如何更改“ CELL_1”的值。这种转变会使它变成“ CELL_20”吗?

我已经阅读了有关MultiIndex,Pandas数据框,系列的文档。我也看过许多StackOverFlow问题,但是没有一个问题能解决我提出的建议,它确实奏效了。我还尝试了对数据进行切片,然后尝试通过重命名来更改它,这没有错误,但是没有产生任何变化。由于未定义多维轴,因此出现各种错误,但是当我定义它们时,我得到了另一个错误,指示该数据框不是MultiIndex数据框。

我错过了什么。

0 个答案:

没有答案