Does DataFrame.index.empty imply DataFrame.empty?

Advertisements

If I have a DataFrame, df, for which df.index.empy is True, will this ALWAYS imply that df.empty is also True?

My intend is to test only df.index.empy when I need to test both conditions (lazy programming style).

>Solution :

Yes, if one of the columns or index is empty, then the shape of your DataFrame is (0, x) or (x, 0) and there is necessarily no data in it, so df.empty will be True.

This is explained in the documentation for DataFrame.empty:

property DataFrame.empty

Indicator whether Series/DataFrame is empty.

True if Series/DataFrame is entirely empty (no items), meaning any of the axes are of length 0.

Yet, the reciprocal is not true, a DataFrame can be empty but either the index or columns can be non empty.

Here is an example:

df = pd.DataFrame(columns=['A', 'B'])

df.shape
# (0, 2)

df.empty
# True

df.index.empty
# True

df.columns.empty
# False

Summary

  • if df.index.empty or df.columns.empty, then df.empty is necessarily True
  • if df.empty, then either of df.index.empty or df.columns.empty is True (or both)

Leave a ReplyCancel reply