Pandas多级索引用于行

3
这本应该是一件简单的事情,但在搜索了几个小时后,我仍然不知道自己错在哪里。

我尝试使用MultiIndexing.from_和其他多种方法,但我就是无法做正确。

我需要像这样的东西:
enter image description here

但我得到的结果却是:
enter image description here 我做错了什么?

import pandas as pd

list_of_customers = ['Client1', 'Client2', 'Client3']
stat_index = ['max', 'current', 'min']
list_of_historic_timeframes = ['16:10', '16:20', '16:30']

timeblock = pd.DataFrame(index=([list_of_customers, stat_index]), columns=list_of_historic_timeframes)
timeblock.fillna(0, inplace=True)

print(timeblock)
1个回答

6
list_of_customers = ['Client1', 'Client2', 'Client3']
stat_index = ['max', 'current', 'min']
list_of_historic_timeframes = ['16:10', '16:20', '16:30']


timeblock = pd.DataFrame(
    0,
    pd.MultiIndex.from_product(
        [list_of_customers, stat_index],
        names=['Customer', 'Stat']
    ),
    list_of_historic_timeframes
)

print(timeblock)

                  16:10  16:20  16:30
Customer Stat                        
Client1  max          0      0      0
         current      0      0      0
         min          0      0      0
Client2  max          0      0      0
         current      0      0      0
         min          0      0      0
Client3  max          0      0      0
         current      0      0      0
         min          0      0      0

太棒了!非常感谢。 即使查看了多个示例,我仍然错误地使用了MultiIndex并使用了错误的from_. - GeorgeLPerkins
现在我卡在了更新特定值上。 我知道如何处理多维Numpy数组,但出于某种原因,我没有正确地处理它们。 我可以更新整行,但是我无法正确指定列。 - GeorgeLPerkins
2
timeblock.loc[('Client1', 'min'), '16:20'] = 3 - piRSquared
再次感谢。我接近成功了,但还没有完全正确。这在示例代码中运行得很好,但在我的真实数据中添加了一个新列。我认为这与原始列标题是日期时间格式有关,而添加的是字符串,但我可以解决这个问题。再次感谢!非常有帮助。 - GeorgeLPerkins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接