以下代码可以正常工作。它从两个变量的列表中创建一个数据框,并进行一些计算。
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)
答案 0 :(得分:1)
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