Dewdrops
Dewdrops

Reputation: 89

How to append rows with concat to a Pandas DataFrame

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?

Upvotes: 5

Views: 14090

Answers (2)

Sumit Jha
Sumit Jha

Reputation: 36

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

Upvotes: 2

Corralien
Corralien

Reputation: 120399

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

Upvotes: 11

Related Questions