简体   繁体   English

如何在 python 的 function 内的多个新创建的数据帧中返回一个非空数据帧?

[英]How to return a non empty data frame among multiple newly created data frames inside a function in python?

I am new to pandas, I have a doubt in returning a data frame from a function.我是 pandas 的新手,我对从 function 返回数据帧有疑问。 I have a function which creates three new data frames based on the parameters given to it, the function has to return only the data frames which are non-empty.我有一个 function ,它根据给定的参数创建三个新的数据帧,function 必须只返回非空的数据帧。 How do I do that?我怎么做?

my code:
 def df_r(df,colname,t1):
    t1_df = pd.DataFrame()
    t2_df = pd.DataFrame()
    t3_df = pd.DataFrame()
    if t1 :
      for colname in df:
           some code
           some code
           t1_df = some data
    if t2 :
      for colname in df:
           some code
           some code
           t2_df = some data
    if t3 :
      for colname in df:
           some code
           some code
           t3_df = some data
    list = [t1_df,t2_df,t3_df]

Now it should return only the t1_df as the parameter was given t1.现在它应该只返回 t1_df,因为参数是 t1。 So I have inserted all three into a list所以我将这三个都插入了一个列表

list = [t1_df,t2_df,t3_df]

how to check if which df is non-empty and return it?如何检查哪个 df 是否为非空并返回?

Just check for empty attribute for each DataFrame只需检查每个DataFrameempty属性

eg.例如。

df = pd.DataFrame()
if df.empty:
    print("DataFrame is empty")

output: output:

DataFrame is empty

pd.empty would return True if DataFrame is empty, else it would return False如果 DataFrame 为空,pd.empty 将返回True ,否则返回False

This would work even if column names are present but are still missing the data.即使存在列名但仍然缺少数据,这也可以工作。

So to answer specific to your case因此,要针对您的情况回答

list = [t1_df,t2_df,t3_df]
for df in list:
    if not df.empty:
        return df

assuming your case has only one of the DataFrame non-empty假设您的案例只有一个 DataFrame 非空

if t1_df.empty != True:
        return t1_df
    elif t2_df.empty !=True:
        return t2_df
    else:
        return t2_df

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM