奇怪的是,Elif,Else的行为

时间:2015-10-06 10:26:04

标签: python python-2.7 if-statement

如果我自己使用以下任何一种情况,它会按预期工作。 (有关所有条件,请参阅更大的代码块)。当我希望exception开启时,我会打印出以下(df['ColumnName'] == 'This Value').any():

打印异常'ColumName2'这打印3次,这告诉我其中一个条件正在满足,它只是没有触发:$

独立工作

if filename.endswith('.csv'):
    print 'File is CSV'        
    df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
    try:
        if (df['ColumnName'] == 'This Value').any():
           final_df = df.drop(df.ix[df['ColumnName'] == 'This Value'].index)
           data = final_df.sort(ascending=True)
           data.to_csv(os.path.join(root, "Edit.csv"), index=False, na_rep="NA")
    except Exception as e:
        print e

但是当用于较大的if时,elifelse似乎没有效果(甚至没有其他命中)。语法似乎是正确的,我所看到的StackOverflow上没有一个答案似乎涵盖了这一点。没有条件是相同的,所以没有看到任何问题,我不完全确定是什么导致了这个问题。

更大,如果,elif,否则

if filename.endswith('.csv'):
    df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
        try:
            if (df['ColumnName'] == 'That Value').any():
                print 'ColumnName and "That Value"'
                final_df = df.drop(df.ix[df['ColumnName'] == 'This Value'].index)
                data = final_df.sort(ascending=True)
                data.to_csv(os.path.join(root, "Edit.csv"), index=False, na_rep="NA")

            elif (df['ColumnName2'] == 'This Value').any():
                print 'ColumnName2 This Value'
                final_df = df.drop(df.ix[df['ColumnName2'] == 'This Value'].index)
                data = final_df.sort(ascending=True)
                data.to_csv(os.path.join(root, "Edit.csv"), index=False, na_rep="NA")

            elif ((df['ColumnName2']=='That Value')).any():
                print 'ColumnName2 That Value'
                final_df = df[df['Dst Port'] != 'Any']
                data = final_df.sort(ascending=True)
                data.to_csv(os.path.join(root, "Edit.csv"), index=False, na_rep="NA")

            elif ((df['ColumnName']=='This Value')).any():
                print 'ColumnName This Value'
                final_df = df[df['Service'] != 'Any']
                data = final_df.sort(ascending=True)
                data.to_csv(os.path.join(root, "Edit.csv"), index=False, na_rep="NA")

            else:
                print 'No Filtering Applied'
                data = df.sort(ascending=True)
                data.to_csv(os.path.join(root, "Edit.csv"), index=False, na_rep="NA")
         except Exception as e:
             print e

修复感谢AnandSKumars评论

if filename.endswith('.csv'):
    try:
        df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
        if 'ColumnName' in df and (df['ColumnName'] == 'This Value').That Value():
            print 'Service and This Value'
            final_df = df.drop(df.ix[df['ColumnName'] == 'This Value'].index)
            data = final_df.sort(ascending=True)
            with open(os.path.join(root,'Edit.csv'), 'a') as f:
                data.to_csv(f, index=False, na_rep="NA")
            os.remove(os.path.join(root, filename))

        elif 'ColumnName2' in df and (df['ColumnName2'] == 'This Value').That Value():
            print 'ColumnName2 and This Value'
            final_df = df.drop(df.ix[df['ColumnName2'] == 'This Value'].index)
            data = final_df.sort(ascending=True)
            with open(os.path.join(root,'Edit.csv'), 'a') as f:
                data.to_csv(f, index=False, na_rep="NA")
            os.remove(os.path.join(root, filename))

        elif 'ColumnName2' in df and ((df['ColumnName2']=='That Value')).That Value():
            print 'ColumnName2 and That Value'
            final_df = df[df['ColumnName2'] != 'That Value']
            data = final_df.sort(ascending=True)
            with open(os.path.join(root,'Edit.csv'), 'a') as f:
                data.to_csv(f, index=False, na_rep="NA")
            os.remove(os.path.join(root, filename))

        elif 'ColumnName' in df and ((df['ColumnName']=='That Value')).That Value():
            print 'Service and That Value'
            final_df = df[df['ColumnName'] != 'That Value']
            data = final_df.sort(ascending=True)
            with open(os.path.join(root,'Edit.csv'), 'a') as f:
                data.to_csv(f, index=False, na_rep="NA")
            os.remove(os.path.join(root, filename))

        else:
            os.remove(os.path.join(root, filename))
    except Exception as e:
        print e

1 个答案:

答案 0 :(得分:1)

最有可能的问题是你有一些csv文件,那些csv中没有一些列。因此,在将其读入数据框后,当您尝试执行@query =时,通过提供 - df['ColumnName']会导致错误。这表示DataFrame中不存在KeyError: 'ColumnName'

但是一旦发生错误,它就被'ColumnName'块捕获,因此没有其他try..exceptif条件触发,因此您无法看到输出

如果您只想满足其中一个条件,那么您可以检查您尝试获取的列是否属于df的一部分。示例 -

elif

同样适用于其他if 'ColumnName' in df and (df['ColumnName'] == 'That Value').any(): 条件。