Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按布尔值索引列_Python_Pandas_Boolean_Dataframe - Fatal编程技术网

Python 按布尔值索引列

Python 按布尔值索引列,python,pandas,boolean,dataframe,Python,Pandas,Boolean,Dataframe,我想保留具有“n”或更多值的列。 例如: > df = pd.DataFrame({'a': [1,2,3], 'b': [1,None,4]}) a b 0 1 1 1 2 NaN 2 3 4 3 rows × 2 columns > df[df.count()==3] IndexingError: Unalignable boolean Series key provided > df[:,df.count()==3] TypeE

我想保留具有“n”或更多值的列。 例如:

> df = pd.DataFrame({'a': [1,2,3], 'b': [1,None,4]})

    a   b
0   1   1
1   2   NaN
2   3   4

3 rows × 2 columns

> df[df.count()==3]
IndexingError: Unalignable boolean Series key provided

> df[:,df.count()==3]
TypeError: unhashable type: 'slice'

> df[[k for (k,v) in (df.count()==3).items() if v]]

    a
0   1
1   2
2   3

这是最好的方法吗?这似乎很可笑。

您可以使用条件列表理解来生成超出阈值的列(例如3)。然后只需从数据框中选择这些列:

# Create sample DataFrame
df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 
                   'b': [1, None, 4, None, 2], 
                   'c': [5, 4, 3, 2, None]})

>>> df_new = df[[col for col in df if df[col].count() > 3]]
Out[82]: 
   a   c
0  1   5
1  2   4
2  3   3
3  4   2
4  5 NaN

您可以使用条件列表理解来生成超出阈值的列(例如3)。然后只需从数据框中选择这些列:

# Create sample DataFrame
df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 
                   'b': [1, None, 4, None, 2], 
                   'c': [5, 4, 3, 2, None]})

>>> df_new = df[[col for col in df if df[col].count() > 3]]
Out[82]: 
   a   c
0  1   5
1  2   4
2  3   3
3  4   2
4  5 NaN

如果要保留具有“n”或更多值的列。例如,我认为n值为4

df = pd.DataFrame({'a': [1,2,3,4,6], 'b': [1,None,4,5,7],'c': [1,2,3,5,8]})
print df

   a   b  c
0  1   1  1
1  2 NaN  2
2  3   4  3
3  4   5  5
4  6   7  8

print df[[i for i in xrange(0,len(df.columns)) if len(df.iloc[:,i]) - df.isnull().sum()[i] >4]]


   a  c
0  1  1
1  2  2
2  3  3
3  4  5
4  6  8

如果要保留具有“n”或更多值的列。例如,我认为n值为4

df = pd.DataFrame({'a': [1,2,3,4,6], 'b': [1,None,4,5,7],'c': [1,2,3,5,8]})
print df

   a   b  c
0  1   1  1
1  2 NaN  2
2  3   4  3
3  4   5  5
4  6   7  8

print df[[i for i in xrange(0,len(df.columns)) if len(df.iloc[:,i]) - df.isnull().sum()[i] >4]]


   a  c
0  1  1
1  2  2
2  3  3
3  4  5
4  6  8

使用
count
生成布尔索引,并将其用作列的掩码:

In [10]:

df[df.columns[df.count() > 2]]


Out[10]:
   a
0  1
1  2
2  3

使用
count
生成布尔索引,并将其用作列的掩码:

In [10]:

df[df.columns[df.count() > 2]]


Out[10]:
   a
0  1
1  2
2  3