简体   繁体   English

如果所有值都是某个字符串,则删除 pandas dataframe 中的列

[英]Removing a column in a pandas dataframe if all the values are a certain string

I have the following dataframe called df.我有以下 dataframe 称为 df。

Sometimes it looks like this (where each value is unique)有时看起来像这样(每个值都是唯一的)

   key   value1 value2 value3
0  key1  value  value  value
1  key2  value  value  value

Sometimes the entire column of value3 are is filled with dashes: '-' .有时value3的整个列都用破折号填充: '-'

   key   value1 value2 value3
0  key1  value  value  -
1  key2  value  value  -

I want to find a command which will drop the column value3 if all the items in the column dashes.我想找到一个命令,如果列中的所有项目都破折号,它将删除列 value3。

I tried using df['value3'].any() and that that returns a '-' .我尝试使用df['value3'].any()并返回一个'-'

Is the right way to do what I want this?做我想做的事情的正确方法是什么?

if df['value3'].any() == '-':
    df = df.drop['value3'] 

Or is there a better way?或者,还有更好的方法?

Use利用

>>> df.loc[:, ~df.eq('-').all()]
    key value1 value2
0  key1  value  value
1  key2  value  value

Compare for not equal by DataFrame.ne and then get all columns with match by DataFrame.any in boolean indexing :通过DataFrame.ne比较不相等,然后在boolean indexing中获取与DataFrame.any匹配的所有列:

print (df.loc[:, df.ne('-').any()])
    key value1 value2
0  key1  value  value
1  key2  value  value

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

相关问题 编写检查所有 Pandas DataFrame 列值是否满足特定值? - Writing check that all pandas DataFrame column values meet a certain values? 通过字符串格式删除Pandas Dataframe中的某些行 - Removing certain rows in Pandas Dataframe by string format 在Dataframe Pandas的列上追加和删除重复值 - Appending and Removing Repeated Values on a column of a Dataframe Pandas 从熊猫数据框中的字符串列中删除b'' - Removing b'' from string column in a pandas dataframe 从Pandas DataFrame列中删除部分字符串 - Removing part of string from Pandas DataFrame column 如何删除 Pandas Dataframe 列中所有值的字符串的最后一个字符? - How to delete the last character of a string for all values in a Pandas Dataframe column? 在不是特定类型的Pandas DataFrame中查找所有值 - Finding All Values in Pandas DataFrame Not of Certain Type Pandas Dataframe:删除 (.) 之后的数字并添加 % 并以特定格式重命名列 - Pandas Dataframe: Removing numbers after (.) and adding % to it and renaming column in certain format 如何为一个 Pandas Dataframe 列中的所有值添加或减去某个百分比? - How to add or subtract certain percent for all values in one Pandas Dataframe column? 如何根据 Pandas 中的另一个 DataFrame 更改 DataFrame 特定列中的值 - How to change values in certain column of DataFrame based on another DataFrame in Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM