gpt4 book ai didi

python代码在函数外部工作,但在函数内部不起作用

转载 作者:行者123 更新时间:2023-12-01 08:27:40 25 4
gpt4 key购买 nike

下面的代码工作得很好。它从两个变量的列表创建一个数据框并进行一些计算。

d = {'VGK':[1], 'VPL':[1]}
parser = lambda timestamp: pd.datetime.strptime(timestamp, '%Y-%m-%d')
etf_tickers = pd.DataFrame(data=d)
etfs = pd.DataFrame([])

for count,ticker in enumerate(etf_tickers):
x = pd.read_csv('{}.csv'.format(ticker), parse_dates=[0], index_col='timestamp',date_parser=parser)
x['{}_logdiff'.format(ticker)] = log(x[ticker]) - log(x[ticker].shift(1))
if etfs.empty:
etfs = x
else:
etfs= etfs.join(x, how='outer')

但是,当我按如下方式移动到函数内部时,它不起作用。我没有收到错误,它只是不生成数据帧。

d = {'VGK':[1], 'VPL':[1]}
parser = lambda timestamp: pd.datetime.strptime(timestamp, '%Y-%m-%d')

def create_frame_logdiffs(inlist,outframe):
outtickers = pd.DataFrame(data=inlist)
outframe = pd.DataFrame([])
for count,ticker in enumerate(outtickers):
x = pd.read_csv('{}.csv'.format(ticker), parse_dates=[0], index_col='timestamp',date_parser=parser)
x['{}_logdiff'.format(ticker)] = log(x[ticker]) - log(x[ticker].shift(1)) #we use the natural log diff to compute retuns defined as the percentage change in price
if outframe.empty:
outframe = x
else:
outframe= outframe.join(x, how='outer')

create_frame_logdiffs(d,etfs)

最佳答案

DataFrame 的作用域是生成它的函数内的本地范围。除非您将 DataFrame 从函数返回到调用的位置,否则您将看不到任何内容。调用函数后,您需要添加一个 return 语句并将输出保存在某个变量中。类似的东西

def create_frame_logdiffs(inlist,outframe):
outtickers = pd.DataFrame(data=inlist)
outframe = pd.DataFrame([])
for count,ticker in enumerate(outtickers):
x = pd.read_csv('{}.csv'.format(ticker), parse_dates=[0], index_col='timestamp',date_parser=parser)
x['{}_logdiff'.format(ticker)] = log(x[ticker]) - log(x[ticker].shift(1)) #we use the natural log diff to compute retuns defined as the percentage change in price
if outframe.empty:
outframe = x
else:
outframe= outframe.join(x, how='outer')
return outframe

outframe = create_frame_logdiffs(d,etfs)
# Do something with the outframe

关于python代码在函数外部工作,但在函数内部不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54120552/

25 4 0
文章推荐: amazon-web-services - 如何使用创建配置文件的 CloudFormation 模板创建 LaunchConfiguration?
文章推荐: php - 如何将页脚中回显的