Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.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_Python 3.x_Pandas - Fatal编程技术网

Python 按行值筛选数据帧时出现问题?

Python 按行值筛选数据帧时出现问题?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有以下数据帧: Col 0 [] 1 [] 2 [(foo, bar), (foo, bar)] 3 [] 4 [] 5 [] 6 [] 7 [(foo, bar), (foo, bar)] 我想删除所有空列表(*): 对于以上内容,我尝试: df = df.loc[df.Col != '[]'] df 及 然而,它们都不起作用。因此,我的问题是如何从数据框中删除所有空列表,如(*)?。您可以使用.str访问器检查列表的长度: df[df.Col.s

我有以下数据帧:

    Col
0   []
1   []
2   [(foo, bar), (foo, bar)]
3   []
4   []
5   []
6   []
7   [(foo, bar), (foo, bar)]
我想删除所有空列表(*):

对于以上内容,我尝试:

df = df.loc[df.Col != '[]']
df


然而,它们都不起作用。因此,我的问题是如何从数据框中删除所有空列表,如(*)?。

您可以使用
.str
访问器检查列表的长度:

df[df.Col.str.len() != 0]

#                        Col
#3  [(foo, bar), (foo, bar)]
#6  [(foo, bar), (foo, bar)]

在数据框中进行切片,就好像是值而不是列表一样,这可能会起作用:

df[df.astype(str)['Col'] != '[]']

df.Col.str.
,在发布此问题之前,我也尝试了该方法。@Tumbweed在本例中,您必须使用
astype
将系列声明为
str
.str
意味着您计划在赋值后操作变量,或者更简单地说,使用它做一些事情。它几乎可以作为前面的函数使用的指示器。e、 g.
str.replace()
如果使用时没有列已经由
str
值组成,或者在使用
astype
时没有声明,则无法正常工作,如果这有帮助,从文档本身-
Series.astype
:将对象强制转换为input numpy.dtype,当copy=True@tumbleweed所以回到
df.Col.str
-
dtype
,作为
str
,还没有被“铸造”:)希望这能有所帮助。祝您今天过得愉快!
df[df.Col.str.len() != 0]

#                        Col
#3  [(foo, bar), (foo, bar)]
#6  [(foo, bar), (foo, bar)]
df[df.astype(str)['Col'] != '[]']