簡體   English   中英

是否有更有效的方法多次調用具有不同參數的函數?

[英]Is there a more efficient way to call functions with different arguments multiple times?

目前我有以下函數迭代Pandas DataFrame( df )列並創建一個計數:

def my_function(my_argument):
    count = 0
    for i, row in df.iterrows(): 
        if row['MyColumn'] == my_argument:
            count += row['MyScore']
    return count

我有很多參數分配給/調用函數 - 現在,我正在做以下事情:

c = my_function('My_String1')
p = my_function('My_String13')
l = my_function('My_String342')
d = my_function('My_String14')
a = my_function('My_String49')
t = my_function('My_String553')
q = my_function('My_String42')
e = my_function('My_String99')
x = my_function('My_String123')
... ETC...

這樣做,工作得很好,但我想知道是否有更實用/有效的方法可以達到相同的結果。

我正在考慮將變量名稱,例如cpld等添加到列表中並形成某種循環 - 如果這甚至可以工作......

因此,也許有點像:

for variable_name in list_of_variables:
    # ??? ... But I'm unaware of what would go here.

或者,是否有使用熊貓的方法?

Pandas有一個內置的方法,value_counts,它的工作方式類似於groupby,但如果你只想要計數,則跳過不需要的東西:

import pandas as pd
df = pd.DataFrame({'x':['a','b','c','d','a','a']})
df.x.value_counts()


a    3
b    1
d    1
c    1
Name: x, dtype: int64

### using groupby:

df.groupby('x').size()

x
a    3
b    1
c    1
d    1
dtype: int64

從那里,您可以過濾掉那些您不想計算的值(或者在value_counts()調用之前執行此操作)。

map(lambda x: my_function(x), list_of_variables)

我建議你嘗試groupby通過數據框支持

但是如果您更喜歡調用自定義函數,我建議將函數參數添加到數組中,如stringList = ["My_String1", "My_String13", ..]

stringList = ["My_String1", "My_String13", ".."]
results = map(my_function, stringList)

map使用列表stringList每個項迭代地調用my_function函數

返回值將存儲在results列表中。

您可以將結果存儲在dict而不是存儲在局部變量中。 然后你可以很容易地使用循環:

results = {}
for var, n in (('c', 1),
               ('p', 13),
               ('l', 342),
              ):
    results[var] = my_function('My_String%d' % n)

暫無
暫無

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

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