Python:在特定列中删除 value=0 行

蔡嚴毅*_*蔡嚴毅 3 python python-3.x pandas

我想在特定列中删除零值的行

>>> df

   salary   age   gender
0   10000    23     1
1   15000    34     0
2   23000    21     1
3     0      20     0
4   28500     0     1
5   35000    37     1
Run Code Online (Sandbox Code Playgroud)

工资和年龄列中的一些数据缺失,第三列,性别是一个二元变量,1 表示男性 0 表示女性。这里的 0 不是缺失的数据,我想删除工资或年龄中的行,这样我就可以得到

>>> df
   salary   age   gender
0   10000    23     1
1   15000    34     0
2   23000    21     1
3   35000    37     1
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 6

选项1

您可以使用pd.DataFrame.loc以下方法过滤数据框:

df = df.loc[~((df['salary'] == 0) | (df['age'] == 0))]
Run Code Online (Sandbox Code Playgroud)

选项 2

或者更聪明的方式来实现你的逻辑:

df = df.loc[df['salary'] * df['age'] != 0]
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为如果薪水或年龄为 0,他们的乘积也将为 0。

选项 3

下面的方法可以很容易地扩展到几个列:

df.loc[(df[['a', 'b']] != 0).all(axis=1)]
Run Code Online (Sandbox Code Playgroud)

解释

  • 在所有 3 种情况下,都会生成用于索引数据帧的布尔数组。
  • 所有这些方法都可以通过使用numpy表示进一步优化,例如df['salary'].values