Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

python 3.x - Why does this for loop give me this error?

I wrote the following loop:

pdFrame = []
for dir, subdir, files in os.walk(path):
    for file in files:
        if glob2.fnmatch.fnmatch(file, '*.gz'):
            columns = ['Gene_ID', file[:file.find('.')]]
            df = pd.read_csv(os.path.join(dir, file), compression='gzip', sep='', names=columns, header=None)
            df = df.set_index('Gene_ID')
            for name, value in df.items():
                pdFrame.append(value)
            data_frame = pd.concat(pdFrame, axis=1, ignore_index=False)
data_frame.to_csv('final_samples.csv', header=True)

However, I keep getting the following error:

"NameError: name 'data_frame' is not defined"

Based on the error, there is some value that must be 'False' , which is why the values aren't posting to the variable, but I don't understand why.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should try declaring data_frame outside of the conditional statement. In a scenario where your if statement doesn't return true, data_frame never gets defined. As a result of that data_frame.to_csv() cannot be called, because it doesn't exist.

Alternatively you can check if data_frame is not null before calling to_csv()

pdFrame = []
data_frame = None
for dir, subdir, files in os.walk(path):
    for file in files:
        if glob2.fnmatch.fnmatch(file, '*.gz'):
            columns = ['Gene_ID', file[:file.find('.')]]
            df = pd.read_csv(os.path.join(dir, file), compression='gzip', sep='', names=columns, header=None)
            df = df.set_index('Gene_ID')
            for name, value in df.items():
                pdFrame.append(value)
            data_frame = pd.concat(pdFrame, axis=1, ignore_index=False)
if data_frame is not None:
    data_frame.to_csv('final_samples.csv', header=True)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...