繁体   English   中英

如何解决 NameError: name 'df' is not defined

[英]How to solve NameError: name 'df' is not defined

import pandas as pd

df = pd.read_csv('JOB205DAYREP.csv', header=0)
df = df.drop([0],axis=0)
df = df.dropna(axis=0, how='all')
df = df.dropna(axis=1, how='all')

df.head(10)

df = pd.DataFrame({})

from dateutil.parser import parse
for index, row in df.iterrows():
    if pd.isnull(row['FLT']) or row ['FLT'] == 'NA':
        df.at[index, 'FLT'] = df.at[index-1, 'FLT']
    
    if pd.isnull(row['STD']) or row ['STD'] == 'NA':
        df.at[index,'STD'] = df.at[index-1, 'STD']

    else:
        row['STD'] = fltdate + row ['STD']
    if not index==0 :
        if pd.isnull(row['VIAOFF']) or row['VIAOFF'] == 'NA':
            df.at[index, 'VIAOFF'] = df.at[index-1, 'VIAOFF']
        if pd.isnull(row['DEP']) or row['DEP'] == 'NA':
            df.at[index, 'DEP'] = df.at[index-1, 'DEP']
df.head(10)

from dateutil.parser import parse
date_string = '21/01/2023'
try :
    if parse(date_string, fuzzy=True, dayfirst=True) is not None:
        print('The string is a valid date.')
    else:
        print('The string is not a valid date.')
except Exception as e:
    error ='error'

此代码使用pandas模块中的read_csv() function 读取 CSV 文件,并删除第一行、所有缺失值的行和所有缺失值的列。

这是csv数据

Output

NameError: name 'df' is not defined 错误被引发是因为 df DataFrame 在第 10 行被重新分配给一个空的 DataFrame:

df = pd.DataFrame({})

你可以解决它删除它,

import pandas as pd

df = pd.read_csv('JOB205DAYREP.csv', header=0)
df = df.drop([0],axis=0)
df = df.dropna(axis=0, how='all')
df = df.dropna(axis=1, how='all')

for index, row in df.iterrows():
    if pd.isnull(row['FLT']) or row ['FLT'] == 'NA':
        df.at[index, 'FLT'] = df.at[index-1, 'FLT']
    
    if pd.isnull(row['STD']) or row ['STD'] == 'NA':
        df.at[index,'STD'] = df.at[index-1, 'STD']

    else:
        row['STD'] = fltdate + row ['STD']
    if not index==0 :
        if pd.isnull(row['VIAOFF']) or row['VIAOFF'] == 'NA':
            df.at[index, 'VIAOFF'] = df.at[index-1, 'VIAOFF']
        if pd.isnull(row['DEP']) or row['DEP'] == 'NA':
            df.at[index, 'DEP'] = df.at[index-1, 'DEP']

# Check if a string is a real valid date
from dateutil.parser import parse
date_string = '21/01/2023'
try :
    if parse(date_string, fuzzy=True, dayfirst=True) is not None:
        print('The string is a valid date.')
    else:
        print('The string is not a valid date.')
except Exception as e:
    error ='error'

如果现在有效,请报告,希望对您有所帮助。

它应该是“read_csv”。 打字错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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