0

doctors and patients arrays are parallel. Data says, for example, the doctor named Benitz has 172 patients in 2017, the doctor Modin has 272 patients in 2019 and so on. I'd like to extract the doctor name data for year 2019 into an array, which is ['Modin' 'Vandergard']. I did this by the code below, but as you see, I firstly use list, append method and then turn the list into an array. I wonder if there is more practical solution without using lists. I mean, is there any way to solve it by just using arrays?

import numpy as np

doctors=np.array(['Benitz','Modin','Leabow','Vandergard'])

patients=np.array([[2017,172],
                   [2019,272],
                   [2016,203],
                   [2019,250]])

doc2019_list=[]
for row in range(0,len(patients)):
    for col in range(0,len(patients[row])):
        if patients[row][col]==2019:
            doc2019_list.append(doctors[row])
doc2019=np.array(doc2019_list)

print(doc2019)

2 Answers 2

1

You can use the years:

>>> patients[:,0]
[2017 2019 2016 2019]

...to create a boolean array of the years equivalent to 2019:

>>> patients[:,0] == 2019
[False  True False  True]

...and use that to access the doctors array:

>>> doctors[patients[:,0] == 2019]
['Modin' 'Vandergard']
Sign up to request clarification or add additional context in comments.

Comments

0

You can use zip functions by combining two lists.

import numpy as np

doctors=np.array(['Benitz','Modin','Leabow','Vandergard'])

patients=np.array([[2017,172],
                   [2019,272],
                   [2016,203],
                   [2019,250]])

doc2019_list = [doctor for doctor, patient in zip(doctors, patients) if patient[0] == 2019]
print(doc2019_list)

If the List comprehension method seems little confusing, look below code, this is the same with above. Further reading Python - List Comprehension

import numpy as np

doctors=np.array(['Benitz','Modin','Leabow','Vandergard'])

patients=np.array([[2017,172],
                   [2019,272],
                   [2016,203],
                   [2019,250]])
doc2019_list = []

for doctor, patient in zip(doctors, patients):
  if patient[0] == 2019:
    doc2019_list.append(doctor)
print(doc2019_list)

Another alternative way with numpy.array

doc2019_list = np.array([doctor for doctor, patient in zip(doctors, patients) if patient[0] == 2019])

2 Comments

so, because numpy has no attribute append, we need to use lists certainly, right?
Numpy has append function Numpy Append. It is your choice, you can process with numpy.append. But numpy.append generates a new array every call, be careful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.