0

I am to write a function that takes 3 arguments: Matrix 1, Matrix 2, and a number p. The functions outputs the number of entries in which the difference between Matrix 1 and Matrix 2 is bigger than p. I was instructed not to use loops.

I was advised to use X.sum() function where X is an ndarray.

I don't know what to do here.

The first thing I want to do is to subtract M2 from M1. Now I have entries, one of which is either or not bigger than p.

I tried to find a way to us the sum function, but I am afraid I can't see how it can help me.

The only thing I can think about is going through the entries, which I am not allowed to. I would appreciate you help in this. No recursion allowed as well.

dhke
  • 15,008
  • 2
  • 39
  • 56
Meitar
  • 145
  • 7
  • 1
    Please reformat your question, having some newlines/whitespace helps a lot in readability. Also, code (like `X.sub()`) would be better between backticks ( `\``) – Wolph Jun 19 '15 at 21:24
  • 1
    Is this a logic problem? Because it sounds like one. – honi Jun 19 '15 at 21:28
  • 1
    How would you do it if matrices 1 and 2 were just single integers? If you would use an `if`, how would you avoid one? (Note that booleans can be directly converted to integers.) Once you know how to do it for single numbers, see if you can broadcast the operations used across entire arrays. – user2357112 Jun 19 '15 at 21:28
  • Maybe it is. Maybe there is a property or a tool I have overlooked. Therefore I ask... – Meitar Jun 19 '15 at 21:28
  • @user2357112 I can do it but right now it requires me to go through every entry and that requires a loop or recursion... – Meitar Jun 19 '15 at 21:30
  • Possible dup of https://stackoverflow.com/questions/7994394/efficient-thresholding-filter-of-an-array-with-numpy – dhke Jun 19 '15 at 21:33
  • 1
    you can turn your array of differences into an array of bools – honi Jun 19 '15 at 21:33
  • The boolean concept worked! Thanks! – Meitar Jun 19 '15 at 21:53

1 Answers1

1
import pandas as pd
# Pick value of P
p = 20
# Instantiate fake frames
a = pd.DataFrame({'foo':[4, 10], 'bar':[34, -12]})
b = pd.DataFrame({'foo':[64, 0], 'bar':[21, 354]})
# Get absolute value of difference
c = (b - a).applymap(abs)
# Boolean slice, then sum along each axis to get total number of "True"s
c.applymap(lambda x: x > p).sum().sum()
Nick Marinakis
  • 1,776
  • 2
  • 10
  • 12