繁体   English   中英

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

[英]remove all rows in pandas dataframe with mixed data types that contain a specific string in multiple columns

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

我已经能够找到解决方案,这些解决方案可以基于整个数据框中的值格式(字符串,数字等)删除行,或者基于特定列中的值删除行,或者从具有几列的数据框中删除行使用他们的名字。

是我找到的最接近的东西,但该解决方案对我而言不起作用,因为由于数量庞大(超过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-未知”的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM