如何在 pandas panel.apply 函数中获取项目名称
How to get item name in pandas panel.apply function
假设 panel1 是我拥有的 pandas 面板,其中包含两个数据帧 df1 和 df2,名称分别为 'item1' 和 'item2'。通过这段代码,
panel1.apply(lambda x: func(x) , axis = [1,2])
我可以将作为单个数据帧的每个项目作为 x 传递给 func(x),并在函数中执行一些操作。但是,我怎么知道x在函数中的项名呢?比如代码是这样的
def func(x):
print x.itemname #obviously this cannot work.
我不想像这样使用for循环,因为它非常耗时,
for item in panel1.items:
panel1[item] = 'some calculations'
你能遍历面板的数据帧吗?你说你担心循环的速度,但我认为它不必很慢。例如,
mypanel = pd.Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'],
major_axis=pd.date_range('1/1/2000', periods=5),
minor_axis=['A', 'B', 'C', 'D'])
def func1(k, x):
print(k)
return x.apply(np.log)
mypanel.apply(lambda x: func1('the wrong name', x)) # 1000 loops, best of 3: 1.01 ms per loop
pd.Panel({k: func1(k, v) for k, v in mypanel.iteritems()}) # 1000 loops, best of 3: 800 µs per loop
如果您使用 apply
,速度差异很小;你应该随意使用 iteritems
.
如果您使用 panel.mean()
等向量化函数,速度 与 有很大不同。但看起来你并没有这样做。
假设 panel1 是我拥有的 pandas 面板,其中包含两个数据帧 df1 和 df2,名称分别为 'item1' 和 'item2'。通过这段代码,
panel1.apply(lambda x: func(x) , axis = [1,2])
我可以将作为单个数据帧的每个项目作为 x 传递给 func(x),并在函数中执行一些操作。但是,我怎么知道x在函数中的项名呢?比如代码是这样的
def func(x):
print x.itemname #obviously this cannot work.
我不想像这样使用for循环,因为它非常耗时,
for item in panel1.items:
panel1[item] = 'some calculations'
你能遍历面板的数据帧吗?你说你担心循环的速度,但我认为它不必很慢。例如,
mypanel = pd.Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'],
major_axis=pd.date_range('1/1/2000', periods=5),
minor_axis=['A', 'B', 'C', 'D'])
def func1(k, x):
print(k)
return x.apply(np.log)
mypanel.apply(lambda x: func1('the wrong name', x)) # 1000 loops, best of 3: 1.01 ms per loop
pd.Panel({k: func1(k, v) for k, v in mypanel.iteritems()}) # 1000 loops, best of 3: 800 µs per loop
如果您使用 apply
,速度差异很小;你应该随意使用 iteritems
.
如果您使用 panel.mean()
等向量化函数,速度 与 有很大不同。但看起来你并没有这样做。