如何删除有条件的行以匹配字符串值

时间:2019-05-30 10:39:38

标签: python-3.x pandas dataframe

我有这个数据框,其中一列的值为“ TRUE”或“ FALSE”。我想摆脱具有列值=“ TRUE”的行。该列的名称为“ is_duplicate”,数据框名称为“ z”。

我尝试了以下方法:

i=0
while(i<len(z)):
    check=z["is_duplicate"].iloc[i:i+1]
    check=check.to_string(index=False)
    if(check=="TRUE"):
        z=z.drop([i],axis=0)
    i=i+1

我还基于相似主题给出的线程尝试了另外两种方法,但是它们都不适合我。

z = z.replace('TRUE', np.nan).dropna()
z=z[z["is_duplicate"] == "FALSE"]

我是编码的新手,即使看起来像最基本的东西,也无法完成它。

2 个答案:

答案 0 :(得分:0)

使用:

StringBuilder

z= z[~z['is_duplicate']=='TRUE']

如果您的z=z[~z['is_duplicate']=='FALSE'] 返回z['is_duplicate'].unique(),则首先将False替换为False(布尔值):

[True False 'FALSE']

然后尝试:

z['is_duplicate'] = z['is_duplicate'].map({'False': False})

答案 1 :(得分:0)

我认为这就是您要寻找的东西

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 360, in run
    prefix=options.prefix_path,
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 247, in move_wheel_files
    prefix=prefix,
  File "/usr/lib/python3/dist-packages/pip/locations.py", line 153, in distutils_scheme
    i.finalize_options()
  File "/usr/lib/python3.6/distutils/command/install.py", line 274, in finalize_options
    raise DistutilsOptionError("can't combine user with prefix, "
distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base```

谢谢