Home > Blockchain >  How to check a column in a row if df.itertuples() is used?
How to check a column in a row if df.itertuples() is used?

Time:10-07

   check_column = 'name'
   for index, row in df.iterrows()
       if check_column in row and row[check_column]:
         pass

If this changes to itertuples():

   check_column = 'name'
   for row in df.itertuples()
       index = row.Index
       ### THIS wont' work
       if check_column in row and row[check_column]:
         pass

When iteruples is used, how to check whether a column exists in it and its value won't be empty? The check_column has to be a variable for checking, not the raw str for my case.

CodePudding user response:

check_column = 'name'
for row in df.itertuples():
    try:
        if row.__getattribute__(check_column):
            print("column exist")
    except:
        print("column dosn't exit")

CodePudding user response:

check_column = 'name'
for row in df.itertuples():
    if check_column in dir(row) and getattr(row, check_column):
        pass
  • Related