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

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

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

问题

# 检查数据框是否为空,如果不为空,则将'test_col'列设置为NaN,否则打印'data is empty'
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

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

答案1

得分: 1

你可以执行一个for循环:

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

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')

答案2

得分: 0

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

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"

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:

确定