Check if single cell value is NaN in Pandas

前端 未结 4 1183
抹茶落季
抹茶落季 2020-12-08 06:53

I just want to check if a single cell in Pandas series is null or not i.e. to check if a value is NaN.

All other answers are for series and arrays, but

相关标签:
4条回答
  • 2020-12-08 07:07

    Just encountered this problem myself and found a solution, imperfect, but works. As noted above, none of these 3 answers are addressing OP's question. Here's an example of my problem which I feel is the same.

    # fill null values of one column with that of another
    f = lambda row: row['A'] if (row['B'].isnull()) else row['B']
    df['B'] = df.apply(f, axis=1)
    
    >>> AttributeError: 'str' object has no attribute 'isnull'
    

    Because the value within a cell of a dataframe is just a primative datatype, you can't use any of pandas built-in methods. So this is what I did.

    f = lambda row: row['A'] if (str(row['B'])=='nan') else row['B']
    

    This actually the only thing I could get to work!

    0 讨论(0)
  • 2020-12-08 07:16

    Try this:

    import pandas as pd
    import numpy as np
    from pandas import *
    
    >>> L = [4, nan ,6]
    >>> df = Series(L)
    
    >>> df
    0     4
    1   NaN
    2     6
    
    >>> if(pd.isnull(df[1])):
            print "Found"
    
    Found
    
    >>> if(np.isnan(df[1])):
            print "Found"
    
    Found
    
    0 讨论(0)
  • 2020-12-08 07:21

    STEP 1.)

    df[df.isnull().any(1)]
    

    ----> Will give you dataframe with rows and column, if any value there is nan.

    STEP 2.)

    this will give you location in dataframe where exactly value is nan. then you could do

    if(**df.iloc[loc_row,loc_colum]==np.nan**):
        print"your code here"
    
    0 讨论(0)
  • 2020-12-08 07:29

    You can use "isnull" with "at" to check a specific value in a dataframe.

    For example:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame([[np.nan, 2], [1, 3], [4, 6]], columns=['A', 'B'])
    

    Yeilds:

        A   B
    0   NaN 2
    1   1.0 3
    2   4.0 6
    

    To check the values:

    pd.isnull(df.at[0,'A'])
    

    -> True

    pd.isnull(df.at[0,'B'])
    

    -> False

    0 讨论(0)
提交回复
热议问题