简体   繁体   中英

UnboundLocalError: local variable 'df' referenced before assignment

I guess I have declared df as pandas.DataFrame() .

Why do the code raise UnboundLocalError ?

import pandas as pd
import statsmodels.api as sm
import numpy as np
from math import log

def half_life(x):
    df = pd.DataFrame()
    df['Close'] = x
    df['ylag'] = df['Close'].shift(1)
    df['deltaY'] = df['Close'] - df['ylag']
    df = df[1:]
    A = np.vstack([df['ylag'], np.ones(len(df['ylag']))]).T
    results = sm.OLS(df['deltaY'], A).fit()
    halflife = -log(2)/results.params[0]
    return halflife

Please help!

DataFrame

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object. Like Series, DataFrame accepts many different kinds of input:

Dict of 1D ndarrays, lists, dicts, or Series
2-D numpy.ndarray
Structured or record ndarray
A Series Another DataFrame

Along with the data, you can optionally pass index (row labels) and columns (column labels) arguments. If you pass an index and / or columns, you are guaranteeing the index and / or columns of the resulting DataFrame. Thus, a dict of Series plus a specific index will discard all data not matching up to the passed index.

If axis labels are not passed, they will be constructed from the input data based on common sense rules.

Note that you are attempting to call Data Frame with no arguments. According to the manual, you must have a data structure and call DataFrame with a data structure argument of a particular type to get a result of a particular type. Look at the examples in the manual that I pointed to to see how pd.DataFrame(d) is set up and print df.type(), df to see what you actually have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM