Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping negative values in a second dataframe, keep the coordinates and replace first dataframe

I have the following dataframes:

df = pd.DataFrame([[1, 5, 1], [2, 6, 2], [3, 7, 3], [4, 8, 4]])
df2 = pd.DataFrame([[1, 5, 10], [3, 6, 2], [1, 9, 3], [4, 8, 4]])

I need to check the subtraction of them (df – df2):

df_sub = pd.DataFrame([[0, 0, -9], [-1, 0, 0], [2, -2, 0], [0, 0, 0]])

When there are negative values, I need to keep their coordinates and substitute for 0 in the first dataframe:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = pd.DataFrame([[1, 5, 0], [0, 6, 2], [3, 0, 3], [4, 8, 4]])

I thought of a function like this:

def find_negative(df):
  coordinates = []
  for column in df.columns:
    for index in df.index:
      if df.loc[index, column] < 0:
        coordinates.append((index, column))
  return coordinates

But how can I apply it to the first dataframe?

>Solution :

You can subtract df2 from df and use df.where:

new_df = df.where(df - df2 >= 0, 0)

Output:

>>> new_df 
   0  1  2
0  1  5  0
1  0  6  2
2  3  0  3
3  4  8  4

>>> new_df.to_numpy().tolist()
[[1, 5, 0], [0, 6, 2], [3, 0, 3], [4, 8, 4]] 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading