Home > Mobile >  Find negative number within iterrow columns
Find negative number within iterrow columns

Time:06-22

I have a dataframe called dataframe and I want to find negative values location. The dataframe looks something like this:

label 123 456
abc 2.01 -9.7
xyz 5.73 5.65
qwe -6.0 3.33

I am wondering if there is a way to run: for index, columns in dataframe.iterrows(): and then inside of the loop, search for negative values row by row. Currently, if I run this with print(column) I get a result such as:

Name: abc
123   2.01
456   -9.7
Name: xyz
123   5.73
456   5.65
Name: qwe
123   -6.0
456   3.33

How do I search these values and get a result of the index, column of a negative number?

CodePudding user response:

You could just access the appropriate index in the series:

for index, series in df.iterrows():
  if series[1] < 0:
    print(f'{index} has negative value')

Or if you want to check any of the numeric values, then:

for index, series in df.iterrows():
  if any(series[1:] < 0):
    print(f'{index} has negative value')

CodePudding user response:

You can use np.where after converting all columns to numeric:

>>> np.where(df.apply(pd.to_numeric, errors='coerce') < 0)
(array([0, 2]), array([2, 1]))
  • Related