python – Pandas中的多维/嵌套DataFrame / Dataset / Panel

我想在pandas数据框或面板中存储一些多维数据,以便我能够返回例如:

>赛跑者A,比赛A的所有时间
> 2015年比赛A的所有时间(和名称)都说

示例数据看起来像这样,请注意并非所有参赛者都拥有所有年份或所有比赛的数据.

任何人都可以建议用熊猫或任何其他方式做到这一点的好方法吗?

Name     | Gender | Age
Runner A | Male   | 35
    Race A
        Year | Time     
        2015 | 2:35:09  
        2014 | 2:47:34
        2013 | 2:50:12
    Race B
        Year | Time
        2013 | 1:32:07

Runner B | Male | 29
    Race A
        Year | Time
        2015 | 3:05:56

Runner C | Female | 32
    Race B
        Year | Time
        1998 | 1:29:43

解决方法:

我想你可以使用Multiindex,然后按slicers选择数据:

import pandas as pd

df = pd.DataFrame({'Time': {('Runner A', 'Male', 35, 'Race A', 2014): '2:47:34', ('Runner C', 'Female', 32, 'Race B', 1998): '1:29:43', ('Runner B', 'Male', 29, 'Race A', 2015): '3:05:56', ('Runner A', 'Male', 35, 'Race A', 2013): '2:50:12', ('Runner A', 'Male', 35, 'Race B', 2013): '1:32:07', ('Runner A', 'Male', 35, 'Race A', 2015): '2:35:09'}})
print (df)
                                   Time
Runner A Male   35 Race A 2013  2:50:12
                          2014  2:47:34
                          2015  2:35:09
                   Race B 2013  1:32:07
Runner B Male   29 Race A 2015  3:05:56
Runner C Female 32 Race B 1998  1:29:43

#index has to be fully lexsorted
df.sort_index(inplace=True)
print (df)
                                   Time
Runner A Male   35 Race A 2013  2:50:12
                          2014  2:47:34
                          2015  2:35:09
                   Race B 2013  1:32:07
Runner B Male   29 Race A 2015  3:05:56
Runner C Female 32 Race B 1998  1:29:43

idx = pd.IndexSlice
print (df.loc[idx['Runner A',:,:,'Race A',:],:])
                                 Time
Runner A Male 35 Race A 2013  2:50:12
                        2014  2:47:34
                        2015  2:35:09

print (df.loc[idx[:,:,:,'Race A',2015],:])
                                 Time
Runner A Male 35 Race A 2015  2:35:09
Runner B Male 29 Race A 2015  3:05:56

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...