【问题标题】:Checking for NaN with math library in a Pandas Dataframe在 Pandas 数据框中使用数学库检查 NaN
【发布时间】:2015-09-10 17:53:41
【问题描述】:

如果我将值 'some value' 分配给数据帧的一个索引,则该列的其他索引将返回 NaN。稍后我想遍历数据帧索引并从NaN 更改值。我正在尝试检查math.isnan(),但它需要一个浮点数作为输入。我可以使用什么函数来执行此检查?

import pandas as pd
import math
BabyDataSet = [['Bob', 968], ['Jessica', 155], ['Mary', 77], ['John', 578], ['Mel', 973]]
df = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births'])

df.ix[1, 'MyValue'] = 'some value'

for index, Name in df.iterrows():
    if math.isnan(df.ix[index, 'MyValue']):
        df.ix[1, 'MyValue'] = 'some other value'
print df

期望的输出:

     Names  Births     MyValue

0      Bob     968     some other value

1  Jessica     155     some value

2     Mary      77     some other value

3     John     578     some other value

4      Mel     973     some other value

【问题讨论】:

    标签: python python-2.7 pandas nan


    【解决方案1】:

    只需使用pandas自己的fillna()

    df.fillna('some other value')
    

    如果您只想更改特定列,您可以提供字典:

    df.fillna({'col_name': 'some other value'})
    

    您甚至可以将不同列中的 NaN 更改为不同的值:

    df.fillna({'col_a': 'some other value', 'col_b': 'other value'})
    

    【讨论】:

    • 如果我只想填写那一列,df['MyValue'].fillna('some other value') 可以吗?
    • 参考我链接到的文档。您甚至可以用不同的值替换不同列中的 NaN。 df.fillna({'col_a':1, 'col_b':2})我也编辑了我的答案。
    • 要使用df.fillna({'MyValue': 'some other value'}),为什么要分配给df比如df = df.fillna({'MyValue': 'some other value'})
    • 只为某个索引替换NaN怎么样?
    • @user2242044 如果您知道列和索引而不是手动设置,fillna 对您没有帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-02-11
    • 2019-11-21
    • 2016-10-16
    • 1970-01-01
    • 2014-03-15
    • 2018-11-08
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多