Windy71
Windy71

Reputation: 909

if else on dataframe header giving KeyError

I have some datafiles from which a user selects via a gui, to determine which pre-processing they need I have an if-else (following example is simplified but produces the traceback) to test which kind of data file it is by the column headers or what is in the comments field.

Data for file which contains a "Comments" header

The following works for a file which has a comments field. When I use it to test a texfile that has no comments field I get an exception - to my way of thinking it should just run the 'else' body when that happens.

Code

if df["Comments"].str.contains("Sclk" or "segs").any():
    print("this might be OPW data")
else:
    print('NOT opw data')

Traceback

Traceback (most recent call last):
  File "/Users/.../Desktop/tk_gui_grid/get_data_01.py", line 47, in <module>
    if df["Comments"].str.contains("Sclk" or "segs").any():
  File "/Users/.../opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/Users/.../opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1618, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1626, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Comments'

Upvotes: 0

Views: 110

Answers (1)

Pulkit Jha
Pulkit Jha

Reputation: 1729

Try this:

if 'Comments' in df.columns and df[df["Comments"].isin(['Sclk', 'segs'])].shape[0] != 0:
    print("this might be OPW data")
else:
    print('NOT opw data')

Upvotes: 1

Related Questions