Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to append 1 data frame with another based on condition

I have 2 dfs. I want to append one with another only if the first df is not null.
Eg:

df1

Name place Animal
Abc China Lion

df2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Name place Animal
Xyz London cheeta
Tom Paris dog

Now I want to append df1 to df2 only if df1 is not null, how do I do that?
what I tried:

for i in len(df1):
    if i > 1:
        df2.append(df1)

but I am getting an error. Is there a better approach?

>Solution :

You can place whatever code you want in the if statement, I just placed a print for "DF1 is empty" as a place holder.

df1 = pd.DataFrame()
df2 = pd.DataFrame({"Name":["ABC", "XYZ"]})

# Check if df1 is empty, if not, concatenate df1 and df2 and reset the index
if df1.empty:
    print("DF1 is empty")
else:
    df2 = pd.concat([df1, df2], ignore_index=True) # You can remove "ignore_index" if you don't want to reset the index
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading