我有一个数据框,其中一列是值列表。我需要选择这些列表不为空的行:
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单元格值与空列表进行比较?
答案 0 :(得分:2)
这是一种做到这一点的方法,但是很有效但是有效:
df[ df.counts.str.len() > 0 ]