python - 熊猫:选择行是一列的列表不为空
问题描述
我有一个数据框,其中有一列值是列表。我需要选择这些列表不为空的行:
import pandas as pd
data = [('words', ['foo', 'bar', 'baz', 'foobar', 'helter', 'skelter']),
('counts', [[1,2,3], [], [5,8], [13,21,34,55], [89], [] ])
]
df = pd.DataFrame.from_items(data)
df
Output:
words counts
0 foo [1, 2, 3]
1 bar []
2 baz [5, 8]
3 foobar [13, 21, 34, 55]
4 helter [89]
5 skelter []
选择这种方式失败:
df[df['counts'] != []]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-db8067c8ac7b> in <module>()
----> 1 df[df['counts'] != []]
/Users/user/usr/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in wrapper(self, other, axis)
859
860 with np.errstate(all='ignore'):
--> 861 res = na_op(values, other)
862 if is_scalar(res):
863 raise TypeError('Could not compare %s type with Series' %
/Users/user/usr/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in na_op(x, y)
763
764 if is_object_dtype(x.dtype):
--> 765 result = _comp_method_OBJECT_ARRAY(op, x, y)
766 else:
767
/Users/user/usr/anaconda/lib/python3.5/site-packages/pandas/core/ops.py in _comp_method_OBJECT_ARRAY(op, x, y)
741 y = y.values
742
--> 743 result = lib.vec_compare(x, y, op)
744 else:
745 result = lib.scalar_compare(x, y, op)
pandas/_libs/lib.pyx in pandas._libs.lib.vec_compare (pandas/_libs/lib.c:14284)()
ValueError: Arrays were different lengths: 6 vs 0
在这种情况下,其他类似的东西df.query
也不起作用。任何想法如何解决这个问题?为什么无法将 pandas 单元格值与空列表进行比较?
解决方案
这是一种很hacky但有效的方法:
df[ df.counts.str.len() > 0 ]
推荐阅读
- python - 如何在 Python 中将水平列表转换为垂直列表并计算术语
- python - python 在一个类的所有对象上尝试 if 语句
- c++ - 什么是 C++ 中的内存位置修改?
- pdf - 使用 Ghostscript 将 PDF 重定向到 Windows 打印机
- java - 如何在嵌套对象的 TableView 中显示数据?
- javascript - 通知用户该电子邮件已经存在。?
- android - 参数类型“double”不能分配给参数类型“PointLatLng”
- javascript - Javascript:将字符串与对象匹配并返回值
- javascript - 汉堡包不会变成 X
- c# - C# MD5 Hash 在超过 2GB 的文件上不一致