我有一个pandas数据框,我希望通过应用基于count函数的过滤器来创建一个新的数据框,这样就只能选择计数等于指定数字的那些列。
例如在下面的数据框中:
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
如果my_variable = 4,则df1应该只包含Col B和Col D以及索引month_end。
我该怎么做?
答案 0 :(得分: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
或者还有count
,已经在计数之前丢下了重复对象:
df.loc[:,df.count().eq(4)]
如果要包括日期列,但它不是索引:
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
答案 1 :(得分:1)
另一个没有循环的解决方案:
s = df.notna().sum(0) == 4
df = df.loc[:, s]
答案 2 :(得分:0)
带有for循环的解决方案:
for col in df.columns:
if (df[col].count() != 4):
df.drop(col, axis=1)