我有一个 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
我希望能够过滤掉 A 列在 B 列中少于 2 行的行,以便上面的表格过滤 A = one:
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
我该怎么做?
最佳答案
一行:
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
在即将发布的 pandas (11.1) 中,新的 filter
method更快更直观地实现这一点:
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
关于python - Pandas :过滤计数小于指定值的数据透视表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17109419/