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

huangapple go评论95阅读模式
英文:

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

问题

  1. # 检查数据框是否为空,如果不为空,则将'test_col'列设置为NaN,否则打印'data is empty'
  2. df['test_col'] = np.nan if not df.empty else print('data is empty')
英文:

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

  1. if not df.empty:
  2. df['test_col'] = np.nan
  3. else:
  4. print('data is empty')

答案1

得分: 1

你可以执行一个for循环:

  1. list_of_dfs = [df1, df2, df3] # 可以有任意数量的数据框
  2. for x in list_of_dfs:
  3. if not x.empty:
  4. x['test_col'] = np.nan
  5. else:
  6. print('数据为空')
英文:

you can do a for loop:

  1. list_of_dfs=[df1,df2,df3] # there can be any number of dfs
  2. for x in list_of_dfs:
  3. if not x.empty:
  4. x['test_col'] = np.nan
  5. else:
  6. print('data is empty')

答案2

得分: 0

  1. def check_empty(df):
  2. df["test_col"] = np.nan if not df.empty else "数据为空"
英文:

Since you wanted a one-liner

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

The output is

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

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

  1. def check_empty(df):
  2. df["test_col"] = np.nan if not df.empty else "data is empty"

huangapple
  • 本文由 发表于 2023年2月18日 03:03:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定