![](/img/trans.png)
[英]What does the Encoding function in R do and is there a Python equivalent?
[英]Is there a Python function that does what mapply do in R
Python 中是否有一個 function 可以做 Mapply 在 R 中做的事情?
基本上我有一個 function 的 n 個輸入列表(每個條目是一個數據幀)和相應的參數列表(每個列表的長度為 n)。
在每個參數列表中,每個參數的position對應輸入列表中輸入的相應position。
現在我希望以我輸入輸入的確切順序獲得結果,或者以列表的形式,每個元素一個數據幀(或矩陣或其他),或者只是一個 dataframe 附加所有結果。 這在 R 中使用 Mapply 很容易實現,但在 python 中,我沒有運氣找到任何可以解決問題的 function。
我沒有嘗試過,但我想到的解決方案之一是 pd.concat 所有列表(包括輸入列表和參數列表)我按列進入一個龐大的列表並將 function 應用於我將提取的每一行行的每個元素填充 function。
這可能有效,但如果實際上有單行解決方案,它看起來會很愚蠢。
這就是我將如何處理 R 中的問題:
result <- mapply(FUN = function(input, parameter1, parameter2) function_of_interest(input, parameter1, parameter2), input = input_list, parameter1 = parameter1_list, parameter2 = parameter2_list,... )
如果我正確理解了這個問題, mapply
中的這個 mapply 示例:
A <- c(1, 2, 3)
B <- c(2, 3, 4)
my_multiplication <- function(x,y){return(x*y)}
C <- mapply(my_multiplication, A, B)
大致相當於這個 Python 代碼:
a = [1, 2, 3]
b = [2, 3, 4]
def my_multiplication(x, y):
return x * y
c = map(my_multiplication, a, b)
c
現在是所謂的迭代器。 如果我過於簡單化, c
可以被視為 function 返回:
a[0] * b[0]
在第一次調用時,
a[1] * b[1]
第二次調用,
a[2] * b[2]
第三次(也是最后一次)調用
i = 0
message = 'a[{}] * b[{}] = {} * {} = {}'
for result in c:
print(message.format(i, i ,a[i], b[i], result))
i += 1
印刷
a[0] * b[0] = 1 * 2 = 2
a[1] * b[1] = 2 * 3 = 6
a[2] * b[2] = 3 * 4 = 12
我的答案似乎是對@Paolo42給出的答案的修改,它只是包裝了“地圖” function 並調用“列表”以擺脫循環:
>>> list(map(my_multiplication, A, B) )
[2, 6, 12]
我也喜歡@Alexander 提供的列表理解解決方案,但我也很欣賞@Paolo42 的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.