如何删除列值在集合中的 DataFrame 行?
How to remove DataFrame rows where a column's values are in a set?
我有一套
remove_set
我想删除数据框中列值在该集合中的所有行。
df = df[df.column_in_set not in remove_set]
这给了我错误:
'Series' objects are mutable, thus they cannot be hashed.
解决这个问题最pandas/pythonic的方法是什么?我可以遍历行并找出要排除的 ilocs,但这似乎有点不雅。
一些示例输入和预期输出。
输入:
column_in_set value_2 value_3
1 'a' 3
2 'b' 4
3 'c' 5
4 'd' 6
remove = set([2,4])
输出:
column_in_set value_2 value_3
1 'a' 3
3 'c' 5
要进行选择,您可以写:
df[~df['column_in_set'].isin(remove)]
isin()
只是检查 column/Series 的每个值是否在一个集合(或列表或其他可迭代对象)中,返回一个布尔系列。
在这种情况下,我们只想在 remove
中包含 而不是 的 DataFrame 行,因此我们使用 ~
和然后使用它来索引 DataFrame。
我有一套
remove_set
我想删除数据框中列值在该集合中的所有行。
df = df[df.column_in_set not in remove_set]
这给了我错误:
'Series' objects are mutable, thus they cannot be hashed.
解决这个问题最pandas/pythonic的方法是什么?我可以遍历行并找出要排除的 ilocs,但这似乎有点不雅。
一些示例输入和预期输出。
输入:
column_in_set value_2 value_3
1 'a' 3
2 'b' 4
3 'c' 5
4 'd' 6
remove = set([2,4])
输出:
column_in_set value_2 value_3
1 'a' 3
3 'c' 5
要进行选择,您可以写:
df[~df['column_in_set'].isin(remove)]
isin()
只是检查 column/Series 的每个值是否在一个集合(或列表或其他可迭代对象)中,返回一个布尔系列。
在这种情况下,我们只想在 remove
中包含 而不是 的 DataFrame 行,因此我们使用 ~
和然后使用它来索引 DataFrame。