0

so I have a hypothetical dataframe:

data = {'sample': [0, 0, 1, 0 , 1, 1], 
        "y": [4, 8 , 3, 2, 3, 9], 
        "x": [3 , 5, 6, 2, 3, 6]}

df = pd.DataFrame(data, columns = ["sample", "y", "x"])

And I want to iterate over each row, and obtaining the values of X and Y if sample equals 1.

I tried the following but I am clearly doing something wrong:


for index, row in df.iterrows():
    ydf = df["y"]
    y.append()

I tried some solutions that I found on the internet but I just don't get it at the moment, even though it is a really simple solution (probably).

Bryan95
  • 13
  • 3
  • You want to "select" or "filter" rows based on a specific column. If you search with similar terms the first result is https://stackoverflow.com/questions/17071871/how-to-select-rows-from-a-dataframe-based-on-column-values – cs95 Mar 08 '21 at 19:41
  • this should give you what you're after: for index, row in df.iterrows(): if (row['sample'] == 1): print("x equals: " + str(row['x'])) print("y equals: " + str(row['y'])) print("") – kat Mar 08 '21 at 20:23
  • I think once you familiarize with dataframes, you'll see that filter/where/select are probably what you'd use. But if you wanted to iterated through each row, and print values if there's a match, then you can use the code I pasted above. – kat Mar 08 '21 at 20:25

0 Answers0