0

How can I make a take certain values of a df by iterating through a df.

I have a df like this:

        A   B   C
    0  10  10  35
    1  11  25  35
    2  12  40  30
    3  10  40  50
    .   .  .   .
   5000 16  12  50

I am trying to retrieve the values of A when B is below 40 and C is below 50. I understand that I should try to iterate somehow like this:

Z = []
for i in range(0, len(df)):
     if df[(df['B'][i] < 40) & (df['C'][i] < 50)]:
        Z = df['A'][i]

But as this is a df I am trying to iterate through all the df like this:

Z = []
for index, row in df.iterrows():
     if df[(df['B'] < 40) & (df['C'] < 50)]:
        Z = df['A'] 

Is my approach wrong? How could I make this cleaner?

Edit: Solution

import numpy as np
import pandas as pd

matrix = np.random.rand(5,3)
df = pd.DataFrame(matrix, columns=['A','B','C'])


newA = df[(df['B'] >= 0.5) & (df['C'] <=0.5 )]
target = newA['A']

credenco
  • 255
  • 2
  • 12
falo8056
  • 85
  • 13
  • 1
    Hi, is [df.where](https://pandas.pydata.org/pandas-docs/stable/referenceapipandas.DataFrame.where.html) here helping? – credenco Mar 10 '20 at 12:42
  • @credenco But how? I used: `Z = np.where(df['B'] < 40) & (df['C'] < 50), df['A'])` But now I get this as result `array(0.01324)` – falo8056 Mar 10 '20 at 12:54
  • 1
    Did the duplicate answer solve your problem? – Josmoor98 Mar 10 '20 at 14:50
  • 1
    `import numpy as np import pandas as pd matrix = np.random.rand(5,3) df = pd.DataFrame(matrix, columns=['A','B','C']) newA = df[(df['B'] >= 0.5) & (df['C'] <=0.5 )] target = newA['A'] ` This is maybe what u are looking for. – credenco Mar 10 '20 at 14:53

0 Answers0