英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论