python - 删除 pandas 数据框中所有具有混合数据类型的行,这些数据类型在多列中包含特定字符串

标签 python pandas

如果某行在任何列中包含“9999-不知道”,我如何删除数据框中的所有行?

我已经找到了解决方案,可以根据整个数据框中的值格式(字符串、数字等)删除行,或者根据特定列中的值删除行,或者从具有以下内容的数据框中删除行使用他们的名字的几列。

This是我找到的最接近的东西,但这个解决方案对我不起作用,因为由于体积庞大(超过 76 列)我无法输入所有列名。

下面是一个示例数据集

pd.DataFrame.from_items([('RespondentId', ['1ghi3g','335hduu','4vlsiu4','5nnvkkt','634deds','7kjng']), ('Satisfaction - Timing', ['9-Excellent','9-Excellent','9999-Don\'t Know','8-Very Good','1-Very Unsatisfied','9999-Don\'t Know']),('Response Speed - Time',['9999-Don\'t Know','9999-Don\'t Know','9-Excellent','9-Excellent','9-Excellent','9-Excellent'])])

删除包含“9999-Don't Know”的 4 行后,输出应如下所示,这样我就可以用清理后的数据编写一个新的 Excel 文件。

pd.DataFrame.from_items([('RespondentId', ['5nnvkkt','634deds']), ('Satisfaction - Timing', ['8-Very Good','1-Very Unsatisfied']),('Response Speed - Time',['9-Excellent','9-Excellent'])]) 

最佳答案

使用

In [677]: df[~(df == "9999-Don't Know").any(axis=1)]
Out[677]:
  RespondentId Satisfaction - Timing Response Speed - Time
3      5nnvkkt           8-Very Good           9-Excellent
4      634deds    1-Very Unsatisfied           9-Excellent

或者

In [683]: df[(df != "9999-Don't Know").all(axis=1)]
Out[683]:
  RespondentId Satisfaction - Timing Response Speed - Time
3      5nnvkkt           8-Very Good           9-Excellent
4      634deds    1-Very Unsatisfied           9-Excellent

一样

In [686]: df[~df.eq("9999-Don't Know").any(axis=1)]
Out[686]:
  RespondentId Satisfaction - Timing Response Speed - Time
3      5nnvkkt           8-Very Good           9-Excellent
4      634deds    1-Very Unsatisfied           9-Excellent

或者

In [687]: df[df.ne("9999-Don't Know").all(axis=1)]
Out[687]:
  RespondentId Satisfaction - Timing Response Speed - Time
3      5nnvkkt           8-Very Good           9-Excellent
4      634deds    1-Very Unsatisfied           9-Excellent

混合列类型,见@PiR的评论df.astype(object)

In [695]: df[df.astype(object).ne("9999-Don't Know").all(axis=1)]
Out[695]:
  RespondentId Satisfaction - Timing Response Speed - Time
3      5nnvkkt           8-Very Good           9-Excellent
4      634deds    1-Very Unsatisfied           9-Excellent

关于python - 删除 pandas 数据框中所有具有混合数据类型的行,这些数据类型在多列中包含特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46225084/

相关文章:

python - 如何使 pygal 将图例分布到 n 列或正确截断?

python - 使用python将excel转换为 Feather 格式

python - 成对样本的带垂直直方图的平行轴点图

python - 根据其他列和字典创建一个新列

pandas - Numpy np.newaxis

python - Folium PolyLine 未显示在 map 上 - 在 Jupyter 笔记本中使用 python 3.6 (anaconda) 的 folium 0.7.0

python - 等高线的位置

Python - 使用 IDLE 和 if - else block 时出现缩进错误,在命令行上工作正常

python - 为什么我的新列在使用 .sample 方法后没有被分配?

python - 将两行中的值附加到 key 对中