Pandas Dataframe:使用计数功能过滤数据

Jam*_*mil 4 python count dataframe pandas

我有一个 Pandas 数据框,我想通过应用基于计数函数的过滤器来从中创建一个新的数据框,以便只选择计数等于指定数字的那些列。

例如在下面的数据框中:

month_end   Col A       Col B       Col C       Col D
200703      NaN          NaN         NaN         NaN
200704      0.084       0.152       0.142      0.0766
200705      0.124       0.123       0.020       NaN 
200706      NaN         0.191       0.091       0.149   
200707      -0.136      0.047       0.135      -0.127
Run Code Online (Sandbox Code Playgroud)

如果 my_variable = 4,则 df1 应仅包含 Col B 和 Col D 以及索引 month_end。

我该怎么做呢?

yat*_*atu 5

你可以做一些类似的事情:

df.loc[:,df.notna().sum(0).eq(4)]

    ColB   ColC
0    NaN    NaN
1  0.152  0.142
2  0.123  0.020
3  0.191  0.091
4  0.047  0.135
Run Code Online (Sandbox Code Playgroud)

或者还有count,它在计数之前已经丢弃了:

df.loc[:,df.count().eq(4)]
Run Code Online (Sandbox Code Playgroud)

如果要包含日期列,并且它不是索引:

ix = df.notna().sum(0).eq(4)
df.loc[:,ix.index[ix].union(['month_end'])]

    ColB   ColC  month_end
0    NaN    NaN     200703
1  0.152  0.142     200704
2  0.123  0.020     200705
3  0.191  0.091     200706
4  0.047  0.135     200707
Run Code Online (Sandbox Code Playgroud)