如何仅对 Python 或 pandas 列表中的特定项目应用某些操作?

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

我有两个列表:

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

我希望这个替换项替换为 replace_items*10 即 [60, 80,200]

因此结果主列表将是:

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

我的试用期:

我收到一个错误:

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

        print(main)

以下是我收到的错误:

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

您可以使用列表理解:

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

输出:

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

因为您最初有一个 pandas 标签,您可能对矢量解决方案感兴趣。

这里使用 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

输出:

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

你可以做到

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

通过使用 enumerate(main) 您可以访问索引和项目

使用pandas你可以做到

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)

输出

[  1   2   3   4   5  60   7  80 200]

说明:使用pandas.Series.isin查找属于replace_items之一的元素,something *= 10是简洁的写法something = something * 10