簡體   English   中英

如何僅對 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簡潔方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM