Home > Blockchain >  Loop through a column of strings and NaN while avoiding NaN
Loop through a column of strings and NaN while avoiding NaN

Time:06-28

Say I have a column called names:

names

name1
NaN
name2
NaN

Entries like name1 and name2 are of type str, and all the NaN entries are of type float, in case you needed to know.

I want to loop through this column to perform changes on the good entries while entirely leaving alone the NaN entries, as such:

for i in range(len(df["names"])):
    if df['names'][i].isnull() == False:
        # do stuff

I've tried isnull(), math.isna(), but I get errors like AttributeError: 'str' object has no attribute 'isnull' and TypeError: expected string or bytes-like object when I try to apply a lambda function instead of using a for loop.

How can I check if each row is not NaN, when all the good entries are strings?

CodePudding user response:

You can use if df['contact'][i] == df['contact'][i] to identify non-NaN values. This leverages the cool property that NaN != NaN.

Though with that said there are other probably vectorized ways to do what you are trying to do.

CodePudding user response:

If you are going to perform changes to the data of non NaN. You can consider this

df.loc[~df['name'].isna()]

This will help you to get the row of data that is not NaN.

  • Related