这些方法列在有关如何取消选择行/列的文档中。
列出构建方法
names
过滤掉值的理解:
cols = ["x"]
foo_filtered = foo[:, [name for name in foo.names if name not in cols]]
或filter
等价物:
cols = ["x"]
foo_filtered = foo[:, list(filter(lambda n: n not in cols, foo.names))]
带有布尔值列表:
cols = ["x"]
foo_filtered = foo[:, [n not in cols for n in foo.names]]
或map
等价物:
cols = ["x"]
foo_filtered = foo[:, list(map(lambda n: n not in cols, foo.names))]
foo_filtered
:
| y z
| int32 int32
-- + ----- -----
0 | 4 7
1 | 5 8
2 | 6 9
[3 rows x 2 columns]
排除方法
remove
也可以使用,但是,这仅限于列选择:
from datatable import f
foo[:, f[:].remove(f['x', 'y'])]
| z
| int32
-- + -----
0 | 7
1 | 8
2 | 9
[3 rows x 1 column]
此方法并非来自文档。
子类方法
如果掩盖列表理解是目标,我们可以为其制作一个包装器tuple
,可用于向names
. 即,使用xor
(或其他所需的操作)成为“排除运算符”。
(我之所以选择列,是xor
因为pandas
用于允许此运算符排除列的列。)
tuple
然后可以将此自定义与 的子类一起使用dt.Frame
来包装属性names
:
from __future__ import annotations
import datatable as dt # v 1.0.0
class TableColumns(tuple):
def __xor__(self, other) -> TableColumns:
if isinstance(other, str):
output = [n != other for n in self]
elif any(isinstance(other, i) for i in [tuple, list, set]):
output = [n not in other for n in self]
else:
raise TypeError(
f'Unsupported type {type(other)} used to filter names'
)
return TableColumns(output)
class MyFrame(dt.Frame):
@property
def names(self) -> TableColumns:
return TableColumns(super(MyFrame, self).names)
那么过滤就可以自然而然地完成了:
框架构造器(使用子类):
foo = MyFrame({'x': [1, 2, 3], 'y': [4, 5, 6], 'z': [7, 8, 9]})
过滤List
:
foo_filtered = foo[:, foo.names ^ ['x', 'z']]
Tuple
:
foo_filtered = foo[:, foo.names ^ ('x', 'z')]
Set
:
foo_filtered = foo[:, foo.names ^ {'x', 'z'}]
foo_filtered
:
| y
| int32
-- + -----
0 | 4
1 | 5
2 | 6
[3 rows x 1 column]
排除单个列str
:
foo_filtered = foo[:, foo.names ^ 'x']
| y z
| int32 int32
-- + ----- -----
0 | 4 7
1 | 5 8
2 | 6 9
[3 rows x 2 columns]