在Pandas中重新索引多索引数据框

时间:2018-10-09 02:46:16

标签: python-3.x pandas

我正在尝试根据另一个多索引数据框为一个多索引数据框重新编制索引。对于单索引的dfs,此方法有效:

[ {Name: "L7 - LO"}, {Name: "% L7 - LO"} ]

输出:

index1 = range(3, 7)
index2 = range(1, 11)
values = [np.random.random() for x in index1]

df = pd.DataFrame(values, index=index1, columns=["values"])

print(df)
print(df.reindex(index2, fill_value=0))

基于 values 3 0.458003 4 0.945828 5 0.783369 6 0.784599 values 1 0.000000 2 0.000000 3 0.458003 4 0.945828 5 0.783369 6 0.784599 7 0.000000 8 0.000000 9 0.000000 10 0.000000 添加新行,并且index2的值设置为y。这就是我的期望。

现在,让我们为多索引df尝试类似的操作:

0

输出:

data_dict = {
    "scan": 1,
    "x": [2,3,5,7,8,9],
    "y": [np.random.random() for x in range(1,7)]
}

index1 = ["scan", "x"]
df = pd.DataFrame.from_dict(data_dict).set_index(index)
print(df)

index2 = list(range(4, 13))
print(df.reindex(index2, level="x").fillna(0))

有什么作用?输出与输入不同:前两个值已被删除。但是其他值-中级(例如 y scan x 1 2 0.771531 3 0.451761 5 0.434075 7 0.135785 8 0.309137 9 0.838330 y scan x 1 5 0.434075 7 0.135785 8 0.309137 9 0.838330 )或更大(例如4或更高)-不存在。我想念什么?

实际的数据帧具有6个索引级别和数十到数百行,但是我认为这段代码捕获了问题。我花了一些时间查看10df.realign,并花了很多时间搜索SO,但是我没有找到解决方案。抱歉,如果重复的话!

2 个答案:

答案 0 :(得分:1)

让我建议一种解决方法:

print(df.reindex(pd.MultiIndex.from_product([df.index.get_level_values(0).unique(), index2], names=['scan', 'x'])).fillna(0))
                y
scan x           
1    4   0.000000
     5   0.718190
     6   0.000000
     7   0.612991
     8   0.609323
     9   0.991806
     10  0.000000
     11  0.000000
     12  0.000000

答案 1 :(得分:0)

以@Sergey的解决方法为基础,这就是我最终得到的结果。我将示例扩展为具有更多级别,更紧密地复制了自己的数据。

生成df:

false

尝试重新编制索引:

Autodesk.Viewing.Initializer()

实施Sergey的解决方法:

GEOMETRY_LOADED_EVENT

注意:如果不包括ProgressiveDisplay,则会为每个级别计算一个倍数(乘积?!?)的数据框。这可能是为什么我的内核之前崩溃的原因;我没有加入data_dict = { "sample": "A", "scan": 1, "meas_time": datetime.now(), "x": [2,3,5,7,8,9], "y": [np.random.random() for x in range(1,7)] } index1 = ["sample", "scan", "meas_time", "x"] df = pd.DataFrame.from_dict(data_dict).set_index(index1) print(df)

这似乎是很奇怪的index2 = range(4, 13) print(df.reindex(labels=index2, level="x").fillna(0)) 行为。我还找到了一种解决方法,其中涉及链接df.reindex( pd.MultiIndex.from_product( [df.index.get_level_values("sample").unique(), df.index.get_level_values("scan").unique(), df.index.get_level_values("meas_time").unique(), index2], names=["sample", "scan", "meas_time", "x"]) ).fillna(0) 。我真的很想知道为什么重新索引会被这样处理。

相关问题