Home > Mobile >  Using a conditional statement to fill a dataframe with 0 as values not working
Using a conditional statement to fill a dataframe with 0 as values not working

Time:04-12

I am working through a lot of dataframes, trying to making calculations on them.

Each one has one column, and six rows. Most of the dataframes are filled, while others either have one or two rows with NaN values or all NaN values. I don't want to replace the dataframes that have one or two NaN values with 0, as that would mess up calculations I'm working on. Rather, I want to just drop those, but for the dataframes that have all NaNs, I want to replace those with 0 so that I can at least get a dummy calculation done on it (otherwise my overall parent for loop stops and won't run). Here is the code I have so far:

if ex_1.isnull.values.any():
    ex_1 = ex_1.dropna(subset=['one'])
    ex_1 = pd.DataFrame(ex_1)
    if ex_1.empty:
       ex_1.one.fillna(value=0, inplace=True)

However, when I run this, the nested if statement does not fill the dataframe with 0, but rather stays empty. This only matters for a few of the dataframes, but I get the error:

TypeError: expected non-empty vector for x

How should I go about fixing this to make it work?

CodePudding user response:

Check whether all the rows are NaN before replacing ex_1.

if ex_1.isnull.values.any():
    if ex_1.dropna(subset=['one']).empty:
        ex_1.one.fillna(value=0, inplace=True)
    else:
        ex_1 = ex_1.dropna(subset=['one'])
        ex_1 = pd.DataFrame(ex_1)
  • Related