Mik*_*ike 4 python pivot-table pandas
我有一个看起来像这样的pandas数据透视表:
C bar foo
A B
one A -1.154627 -0.243234
three A -1.327977 0.243234
B 1.327977 -0.079051
C -0.832506 1.327977
two A 1.327977 -0.128534
B 0.835120 1.327977
C 1.327977 0.838040
Run Code Online (Sandbox Code Playgroud)
我希望能够过滤掉列B中列A少于2行的行,这样上面的表将过滤A = 1:
C bar foo
A B
three A -1.327977 0.243234
B 1.327977 -0.079051
C -0.832506 1.327977
two A 1.327977 -0.128534
B 0.835120 1.327977
C 1.327977 0.838040
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
在一行中:
In [64]: df[df.groupby(level=0).bar.transform(lambda x: len(x) >= 2).astype('bool')]
Out[64]:
bar foo
two A 0.944908 0.701687
B -0.204075 0.713141
C 0.730844 -0.022302
three A 1.263489 -1.382653
B 0.124444 0.907667
C -2.407691 -0.773040
Run Code Online (Sandbox Code Playgroud)
在即将发布的pandas(11.1)中,新filter方法可以更快,更直观地实现这一目标:
In [65]: df.groupby(level=0).filter(lambda x: len(x['bar']) >= 2)
Out[65]:
bar foo
three A 1.263489 -1.382653
B 0.124444 0.907667
C -2.407691 -0.773040
two A 0.944908 0.701687
B -0.204075 0.713141
C 0.730844 -0.022302
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1275 次 |
| 最近记录: |