子类化pandas类似乎是一个常见的需求,但我找不到关于这个主题的参考.(似乎熊猫开发者仍在努力:https://github.com/pydata/pandas/issues/60).
关于这个主题有一些SO主题,但我希望这里有人可以提供一个更系统的帐户,目前最好的方法是将pandas.DataFrame子类化,满足两个,我认为,一般要求:
import numpy as np
import pandas as pd
class MyDF(pd.DataFrame):
# how to subclass pandas DataFrame?
pass
mydf = MyDF(np.random.randn(3,4), columns=['A','B','C','D'])
print type(mydf) # <class '__main__.MyDF'>
# Requirement 1: Instances of MyDF, when calling standard methods of DataFrame,
# should produce instances of MyDF.
mydf_sub = mydf[['A','C']]
print type(mydf_sub) # <class 'pandas.core.frame.DataFrame'>
# Requirement 2: Attributes attached to instances of MyDF, when calling standard
# methods of DataFrame, should still attach to the output. …Run Code Online (Sandbox Code Playgroud) 我正在 pandas 中使用多重索引数据框,想知道是否应该对行或列进行多重索引。
我的数据看起来像这样:

代码:
import numpy as np
import pandas as pd
arrays = pd.tools.util.cartesian_product([['condition1', 'condition2'],
['patient1', 'patient2'],
['measure1', 'measure2', 'measure3']])
colidxs = pd.MultiIndex.from_arrays(arrays,
names=['condition', 'patient', 'measure'])
rowidxs = pd.Index([0,1,2,3], name='time')
data = pd.DataFrame(np.random.randn(len(rowidxs), len(colidxs)),
index=rowidxs, columns=colidxs)
Run Code Online (Sandbox Code Playgroud)
在这里,我选择对列进行多重索引,理由是 pandas 数据帧由系列组成,而我的数据最终是一堆时间序列(因此这里按时间进行行索引)。
我有这个问题,因为多重索引的行和列之间似乎存在一些不对称。例如,在本文档网页中,它显示了query行多索引数据帧的工作原理,但如果数据帧是列多索引的,则文档中的命令必须替换为类似df.T.query('color == "red"').T.
我的问题可能看起来有点愚蠢,但我想看看数据帧的多索引行与列之间在便利性上是否有任何差异(例如query上面的情况)。
谢谢。