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

How to apply some operations on only specific items in the list in Python or pandas?

I have two lists:

main = [1,2,3,4,5,6,7,8,20]
replace_items = [6,8,20]

I want this replace items to replace with replace_items*10 i.e [60, 80,200]

So the result main list would be:

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

main = [1,2,3,4,5,60,7,80,200]

My trial:

I am getting an error:

for t in replace_items:
    for o in main:
       
        main = o.replace(t, -(t-100000), regex=True)

        print(main)

following is the error I am getting:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-592-d3f3f6915a3f> in <module>
     14         main = o.replace(t, -(t-100000), regex=True)
---> 15         print(main)
     
            

TypeError: replace() takes no keyword arguments
    

>Solution :

As you initially had a pandas tag, you might be interested in a vectorial solution.

Here using numpy

import numpy as np

main = np.array([1,2,3,4,5,6,7,8,20])
replace_items = np.array([6,8,20])  # a list would work too

main[np.in1d(main, replace_items)] *= 10

output:

>>> main
array([  1,   2,   3,   4,   5,  60,   7,  80, 200])
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