Jerry
Jerry

Reputation: 77

My for loop doesn't count values from another column in dataframe

I'm completely lost why my for loop doesn't append the value from another column.

My dataframe looks like this

enter image description here

and my code is like this

i = -1
open_line = []

for line in df["line 1"]:
    idx = i + 1
    if (0 < line < 1000 and df.iloc[idx]["line 2"] < 0):
        open_line.append(df.iloc[idx]["line 2"])
    elif line == 1000 and df.iloc[idx]["line 2"] == 1000:
        open_line.append("NAN")
    elif line == 1000 and 0 < df.iloc[idx]["line 2"] < 1000:
        open_line.append("NAN")
    elif line < 0:
        open_line.append(line)

When I print open_line I get

['NAN', 'NAN', -1]

The problem is when first if statement is passed at row 3 it doesn't append -9 to my list but it just goes on.

Thanks for the help.

Upvotes: 1

Views: 36

Answers (1)

Laurent
Laurent

Reputation: 13518

The problem comes from the fact that idx is never incremented.

Replace:

  • i = -1 with idx = -1

  • and idx = i + 1 with idx = idx + 1

Then print(open_line) outputs ['NAN', 'NAN', -9, -1, -3, -3]

A more efficient way to do it would be like this:

df.loc[(df["line 1"] > 0) & (df["line 1"] < 1_000), "open_line"] = df.loc[
    (df["line 1"] > 0) & (df["line 1"] < 1_000), "line 2"
]
df.loc[
    (df["line 1"] == 1_000) & (df["line 2"] > 0) & (df["line 2"] <= 1_000), "open_line"
] = "NAN"
df.loc[df["line 1"] < 0, "open_line"] = df.loc[df["line 1"] < 0, "line 1"]

open_line = [i if isinstance(i, str) else int(i) for i in df["open_line"]]

Then print(open_line) outputs ['NAN', 'NAN', -9, -1, -3, -3]

Upvotes: 1

Related Questions