[英]Replace a row in Pandas DataFrame with 'NaN' based on condition
I have a Pandas DataFrame called df
(378000, 82) and I would like to replace the entire row with NaN
based on a specific condition.我有一个名为
df
(378000, 82) 的 Pandas DataFrame ,我想根据特定条件用NaN
替换整行。 The condition is for any value in the column df.halon_gas
that is >20, I want to replace that entire row with NaN
.条件是
df.halon_gas
列中大于 20 的任何值,我想用NaN
替换整行。 This is the way I want to filter my data so I don't lose the index values.这是我想要过滤数据的方式,这样我就不会丢失索引值。
Thanks!谢谢!
If you're fine with the rows being gone then I suggest you do this:如果您对消失的行感到满意,那么我建议您这样做:
df.reset_index(level=0, inplace=True)
df = df[df.halon_gas <= 20]
df.set_index("index", inplace=True)
Whats happening here is the following:这里发生的情况如下:
First of all get all indexes of values, that are below 20首先获取值的所有索引,低于 20
idx = df[df.halon_gas >= 20].index
Then set the values for all columns and all columns which are below 200 to None然后将所有列和所有低于 200 的列的值设置为 None
df.set_value(idx, df.columns , None)
This should write None/Nan in the rows with the value below 20这应该在值低于 20 的行中写入 None/Nan
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.