Home > Net >  How to append 1 data frame with another based on condition
How to append 1 data frame with another based on condition

Time:07-25

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

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?

CodePudding user response:

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
  • Related