'Replace column with another array using python

I have one A array of (5x5) elements and a second B array of (5x1). Now I want to replace the column of A with B. My array is

A=array([[1, 2, -3, 4, 5],[1, 2, -3, -4, 5],[-1, 2, -3, -4, 5],[-1, -2, -3, -4, 5],[-1, -2, -3, -4, -5]])
and 
B=array([-10. , -11.5, -13. , -14.5, -16. ])

So it should replace every column with B when the first negative number encounters. For example, in the first column of A, the first negative element is at A[2][0] (-1), so the first column of A replaces with B[2], in the second column the first negative element is at A[3][1] and that column replace with B[3], etc. So my final output is

A=(alpha[2],alpha[3],alpha[0],alpha[1],alpha[4])= (-13.0, -14.5, -10.0, -11.5, -16.0)  

So far my code is

A=array([[1, 2, -3, 4, 5],[1, 2, -3, -4, 5],[-1, 2, -3, -4, 5],[-1, -2, -3, -4, 5],[-1, -2, -3, -4, -5]])
B=np.linspace(-10,-16,5)
for i in range(len(B)):
  A[:,i][A[:,i]<0]=alpha[i]

But this is not giving the correct answer.

Thank you in advance!



Solution 1:[1]

Try getting all values using batch operations, and use the minimum of API calls in the loop, like this:

function main() {
  // spreadsheet
  const ssID = '1cpR6AVVpk9TF4_I38IFYPPOqk-_bSROHgVVYdaXLXOI';
  const sheet = SpreadsheetApp.openById(ssID).getSheetByName('car_number');
  const data = sheet.getDataRange().getValues();
  const labels = data.shift();
  const firstColumn = data.map(row => row[0]);
  // form
  const formID = '14foKaEoUA_lhDmJTJExwQ5vavsGJShWm_x1kaANLhwU';
  const form = FormApp.openById(formID);
  const items = form.getItems();
  const itemIds = items.map(item => item.getId());
  const itemTitles = items.map(item => item.getTitle());
  // action
  labels.forEach((label, rowIndex) => {
    const options = firstColumn.filter((option, optionIndex) => optionIndex >= rowIndex && option !== '');
    updateDropdownUsingTitle_(items, itemTitles, label, options);
  });
}

function updateDropdownUsingTitle_(items, itemTitles, title, values) {
  const pos = itemTitles.indexOf(title);
  if (pos !== -1) {
    updateDropdown_(items[pos], values);
  }
}

function updateDropdown_(item, values) {
  item.asListItem().setChoiceValues(values);
}

With this pattern, the only API calls in the loop are in item.asListItem().setChoiceValues(values).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 doubleunary