check if a dataframe is not empty in 1 line of code in python

Question:

I am checking if a dataframe is empty or not but I want to do this in 1 line of code as I am checking many dataframe’s and don’t want to repeat the same code again as it becomes chunky. example is below. great if anyone can help

if not df.empty:
   df['test_col'] = np.nan
else:
   print('data is empty')
Asked By: Zack

||

Answers:

you can do a for loop:

list_of_dfs=[df1,df2,df3] # there can be any number of dfs
for x in list_of_dfs:
  if not x.empty:
   x['test_col'] = np.nan
  else:
   print('data is empty')
Answered By: God Is One

Since you wanted a one-liner

df["test_col"] = np.nan if not df.empty else "data is empty"

The output is

        Apples  Pears   Peaches Grapes  test_col
0       12      23      0       4       NaN
1       10      0       0       4       NaN
2       12      16      12      5       NaN
3       6       0       0       11      NaN

What I would do is that I would make it into a function as follows:

def check_empty(df):
    df["test_col"] = np.nan if not df.empty else "data is empty"
Answered By: batuhaneralp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.