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

Time:11-15

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:

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
    

CodePudding user response:

You can use list comprehension:

main = [x * 10 if x in replace_items else x for x in main]

Output:

print(main)
[1, 2, 3, 4, 5, 60, 7, 80, 200]

CodePudding user response:

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])

CodePudding user response:

You can do this

for (index,mainItems) in enumerate(main) : 
    if mainItems in replace_items : 
        main[index] *= 10 

By using enumerate(main) you have access to both index and item

CodePudding user response:

Using pandas you can do

import pandas as pd
main = pd.Series([1,2,3,4,5,6,7,8,20])
replace_items = [6,8,20]
main[main.isin(replace_items)] *= 10
print(main.values)

Output

[  1   2   3   4   5  60   7  80 200]

Explanation: use pandas.Series.isin to find elements which are one of replace_items, something *= 10 is concise way to write something = something * 10

  • Related