有条件地从熊猫数据框中删除行

时间:2020-07-17 21:35:45

标签: python pandas dataframe

我试图有条件地从熊猫数据框中删除行并遇到麻烦。例如,在下面的示例中,我想从数据框中删除第二行和第三行。

import pandas as pd

df = pd.DataFrame([
    [12, 10, 7, 0],
    [11, 0, 0, 3],
    [0, 0, 0, 0],
    [0, 6, 7, 5],
    [4, 11, 3,4],
    [5, 2, 5, 0]],
    columns=["num1", "num2","num3","num3"])

我尝试过:

df.loc[~(df['num2','num3']==0).all(axis=1)]

但收到错误“ TypeError:只有整数标量数组可以转换为标量索引”

我还按照下面的建议尝试了此操作,并获得了意外的输出: enter image description here

2 个答案:

答案 0 :(得分:2)

尝试

df.loc[(df['num2']!=0) & (df['num2']!=0)]

答案 1 :(得分:1)

neall一起使用:

df = df.loc[df[['num2','num3']].ne(0).all(axis=1)]
print(df)
   num1  num2  num3  num4
0    12    10     7     0
3     0     6     7     5
4     4    11     3     4
5     5     2     5     0

这是我执行的屏幕截图:

Output