Search code examples
pythonarraysnumpyarcpy

How to calculate the proportion of each cell in the matrix to the sum of the column?


I am an absolute beginner in using python.

My problem is the following ....

Example:

On the basis of the table which is not defined by the number of columns and rows, you need to evaluate expressions as shown...

    A  B  C  D  E .. n
 a  1  3  5  3  5 .. n
 b  4  3  4  2  6 .. n
 .  .  .  .  .  . .. n
 .
 m  .  .  .  .  . .. n
    X1 X2 X3 X4 X5.. Xn

X1 = (Aa / SUM A)^2 + (Ab / SUM A)^2+ .. +(Am / SUM A)^2
X2 = (Ba / SUM B)^2 + (Bb / SUM B)^2+ .. +(Bm / SUM B)^2
.
.
Xn ....

Does anyone have an idea how to create an expression that solves the problem shown in Figure?

I should be to existing code insert defined an expression....

  values = [] # store the sum values here.
  fields = arcpy.ListFields(fc, "*")

  # get the OID/FID field name to skip
  desc = arcpy.Describe(fc)
  if desc.hasOID:
      OIDname = desc.OIDFieldName.upper()
  else:
      OIDname = ""

  for field in fields:
      if field.name.upper() != OIDname: # skip the OID/FID field.
         if field.type in ("Double", "Integer", "Single"):
              # sum each suitable field, but not the NULL ones - they would be bad
              with arcpy.da.SearchCursor(fc,field.name,field.name + " is not NULL") as sCur:
                  thisValue = 0
                  for row in sCur:
                      thisValue = ???????? # expression -- (A1 / SUM A)^2+...
                  values.append(thisValue) # this will be the inserted row
              fieldNameList.append(field.name) 

  with arcpy.da.InsertCursor(fc, fieldNameList) as cur:
      cur.insertRow(values)

In the code I use arcpy and numpy ...

thanks in advance


Solution

  • Using NumPy's bradcasting rules you can avoid the loops doing something like:

    s = a.sum(axis=0)
    x = ((a/s)**2).sum(axis=0)
    

    where a is your m X n matrix.