当apply函数返回一个系列时,我很好奇pandas groupby-apply的行为.
当系列具有不同的长度时,它返回一个多索引系列.
In [1]: import pandas as pd
In [2]: df1=pd.DataFrame({'state':list("AABBB"),
...: 'city':list("vwxyz")})
In [3]: df1
Out[3]:
city state
0 v A
1 w A
2 x B
3 y B
4 z B
In [4]: def f(x):
...: return pd.Series(x['city'].values,index=range(len(x)))
...:
In [5]: df1.groupby('state').apply(f)
Out[5]:
state
A 0 v
1 w
B 0 x
1 y
2 z
dtype: object
Run Code Online (Sandbox Code Playgroud)
这返回一个Series对象.
但是,如果每个系列都具有相同的长度,那么它将其转换为a DataFrame.
In [6]: df2=pd.DataFrame({'state':list("AAABBB"),
...: 'city':list("uvwxyz")})
In [7]: df2
Out[7]:
city state
0 …Run Code Online (Sandbox Code Playgroud) 假设我有一个可视化,由面板按一些分类变量进行格式化,每页一个面板.我想循环遍历面板并将每个图像导出到一个文件,文件名与分类变量匹配.
根据一些已发布的示例,图像导出完全正常.但是,实际获取当前面板的名称时遇到很多麻烦,以便我可以正确命名图像.
这是我的代码:
from Spotfire.Dxp.Application.Visuals import VisualContent
from System.Drawing import Bitmap, Graphics, Rectangle, Point
from System.IO import Path
import re
vc=viz.As[VisualContent]() #viz is the visualization parameter passed to the script
trellis=vc.Trellis
originalIndex=trellis.ActivePageIndex
outputDir=Document.Properties["imageOutputDir"]
for i in range(trellis.PageCount):
#move to the right page
trellis.ActivePageIndex=i
#make the actual image -
viz_r = Document.ActivePageReference.GetVisualBounds(viz)
width=viz_r.Width
height=viz_r.Height
bm = Bitmap(width,height)
g = Graphics.FromImage(bm)
g.TextRenderingHint = g.TextRenderingHint.AntiAlias
r=Rectangle(0, 0, width,height)
vc.Render(g, r)
#save the image
name="%d"%i
#here we would like to instead get the current …Run Code Online (Sandbox Code Playgroud) L是行上具有多索引的数据帧列表.
pd.concat(L,axis=1)
Run Code Online (Sandbox Code Playgroud)
我得到以下错误(来自Categorical构造函数categorical.py):
TypeError:'values'未排序,请通过传入categories参数明确指定类别顺序.
它显然与我的数据框中的值有关,因为如果我以某种方式限制数据,我可以使它工作.
例如所有这些工作
a=pd.concat(L[0:6],axis=1)
b=pd.concat(L[6:11],axis=1)
c=pd.concat(L[3:9],axis=1)
Run Code Online (Sandbox Code Playgroud)
但
d=pd.concat(L[0:11],axis=1)
Run Code Online (Sandbox Code Playgroud)
失败.
pd.concat([x.iloc[0:1000,:] for x in L[0:11]],axis=1)
Run Code Online (Sandbox Code Playgroud)
也有效.我已经经历了它破坏的边缘情况,而对于我的生活,我没有看到任何可能在这些行中冒犯的东西.有没有人对我应该寻找什么有一些想法?