Home > OS >  How to append rows with concat to a Pandas DataFrame
How to append rows with concat to a Pandas DataFrame

Time:03-21

I have defined an empty data frame with:

insert_row = {
    "Date": dtStr,
    "Index": IndexVal,
    "Change": IndexChnge,
}
data = {
    "Date": [],
    "Index": [],
    "Change": [],
}
df = pd.DataFrame(data)
df = df.append(insert_row, ignore_index=True)

df.to_csv(r"C:\Result.csv", index=False)
driver.close()

But I get the below deprecation warning not to use df.append every time I run the code

enter image description here

Can anyone suggest how to get rid of this warning by using pandas.concat?

CodePudding user response:

Create a dataframe then concat:

insert_row = {
    "Date": '2022-03-20',
    "Index": 1,
    "Change": -2,
}

df = pd.concat([df, pd.DataFrame([insert_row])])
print(df)

# Output
         Date  Index  Change
0  2022-03-20    1.0    -2.0

CodePudding user response:

Covert insert_row to dataframe first then use concat, try this

insert_row = {"Date": ["dtStr"],"Index": ["NiftyVal"],"Change": ["iftyChnge"]}
data = {"Date": [],"Index": [],"Change": []}
df1 = pd.DataFrame(insert_row)
df2 = pd.DataFrame(data)
Result = [df1,df2]
df = pd.concat(Result, ignore_index=True)
print(df)

#output

Date     Index     Change

0 dtStr NiftyVal iftyChnge

  • Related