Skip to main content
 首页 » 编程设计

python之如何在 Python 中对数据数组执行我的函数

2025年02月15日9JeffreyZhao

在 MATLAB 中,如果我编写自己的函数,我可以将一个数组传递给该函数,它会自动处理它。我正在尝试用另一种数据科学语言 Python 做同样的事情,但它没有处理它。

有没有一种简单的方法可以做到这一点,而不必在每次我想对数组中的所有值进行操作时都进行循环?那还有很多工作要做!似乎在 Python 中工作的伟大思想家以前会有这样的需求。

我尝试将数据类型切换为 list(),因为它是可迭代的,但这似乎不起作用。我仍然收到一个错误,基本上说它不需要数组对象。

这是我的代码:

import scipy 
from collections import deque 
import numpy as np 
import os 
from datetime import date, timedelta 
 
def GetExcelData(filename,rowNum,titleCol): 
    csv = np.genfromtxt(filename, delimiter= ",") 
    Dates = deque(csv[rowNum,:]) 
    if titleCol == True: 
        Dates.popleft() 
    return list(Dates) 
 
def from_excel_ordinal(ordinal, _epoch=date(1900, 1, 1)): 
    if ordinal > 59: #the function stops working here when I pass my array 
        ordinal -= 1  # Excel leap year bug, 1900 is not a leap year! 
    return _epoch + timedelta(days=ordinal - 1)  # epoch is day 1 
 
os.chdir("C:/Users/blahblahblah") 
filename = "SamplePandL.csv" 
Dates = GetExcelData(filename,1,1) 
Dates = from_excel_ordinal(Dates) #this is the call with an issue 
print(Dates) 

请您参考如下方法:

好吧,您可以为此使用 map 函数。

Dates = from_excel_ordinal(Dates) 

用下面的代码替换上面的代码行

Dates = list(map(from_excel_ordinal,Dates)) 

在上面的代码中,对于日期中存在的每个值,将调用函数 from_excel_ordinal。最后它被转换成列表并存储到日期中。