python - 根据 Pandas 中的列表删除行

标签 python pandas dataframe

node1    node2    weight  date


3         6     1        2002

2          7     1        1998

2          7     1        2002

2          8     1        1999

2         15     1        2002

9        15     1        1998

2         16     1        2003

2         18     1        2001

我想删除具有值 [3, 7, 18] 的行。这些值可以在任何行 node1node2.

最佳答案

In [8]: new = df[~df.filter(regex='^node').isin([3,7,18]).any(1)]

In [9]: new
Out[9]:
   node1  node2  weight  date
3      2      8       1  1999
4      2     15       1  2002
5      9     15       1  1998
6      2     16       1  2003

一步一步:

In [164]: df.filter(regex='^node').isin([3,7,18])
Out[164]:
   node1  node2
0   True  False
1  False   True
2  False   True
3  False  False
4  False  False
5  False  False
6  False  False
7  False   True

In [165]: df.filter(regex='^node').isin([3,7,18]).any(1)
Out[165]:
0     True
1     True
2     True
3    False
4    False
5    False
6    False
7     True
dtype: bool

In [166]: ~df.filter(regex='^node').isin([3,7,18]).any(1)
Out[166]:
0    False
1    False
2    False
3     True
4     True
5     True
6     True
7    False
dtype: bool

In [167]: df[~df.filter(regex='^node').isin([3,7,18]).any(1)]
Out[167]:
   node1  node2  weight  date
3      2      8       1  1999
4      2     15       1  2002
5      9     15       1  1998
6      2     16       1  2003

关于python - 根据 Pandas 中的列表删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46978264/

相关文章:

python - 如何计算列 Pandas 数据框中列表的平均值

Python:从数据框创建邻接矩阵

python - 如何在 pandas Dataframe 中实现我自己的公式?

r - 如何修剪数据框的开头

python - Shapefile 到 2D 网格作为稀疏矩阵

python - 动态导入的模块认为它没有类

python - 当您知道列和行引用时如何更改数据框中的字段值

python : nested json to dataframe

python - 在 Python 中使用 OpenCV 对点进行不失真时的错误结果

python - 为什么第 256 行和第 256 列没有蓝线?