简体   繁体   English

根据条件将 Pandas DataFrame 中的一行替换为“NaN”

[英]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:这里发生的情况如下:

  1. The Index gets reset so you have an extra Column with the Index Values pre Removal.索引被重置,因此您有一个额外的列,其中包含删除前的索引值。
  2. Only the rows where df.halon_gas <= 20 are kept.仅保留 df.halon_gas <= 20 的行。
  3. The old Index values are set to be the Index for the DataFrame again.旧的索引值再次设置为 DataFrame 的索引。

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.

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