GSatterwhite
GSatterwhite

Reputation: 301

df.append is creating new columns instead of appending to existing ones

im writing a program that calculates that creates a data frame from two variables that are calculated every minute as part of a loop.

Here I created the initial entry to the dataframe:

columnsMA = ['Time', 'Fast MA:', 'Slow MA:']
dfMA = pd.DataFrame([[datetime.now().strftime("%m/%d/%Y, %H: %M"), 
                      fastMA, slowMA]], columns=columnsMA)

Here is correct output for this first minute:

                 Time  Fast MA:  Slow MA:
0  03/05/2019, 21: 40   3827.75    3826.9

A minute later I am appending the new minute's calculations of fast MA and Slow MA with these lines:

    seriesMA = [[datetime.now().strftime("%m/%d/%Y, %H: %M"), fastMA, 
                 slowMA]]
    dfMA = dfMA.append(seriesMA, ignore_index=True)

But the output after this is:

                    0       1       2  Fast MA:  Slow MA:                Time
0                 NaN     NaN     NaN   3827.75    3826.9  03/05/2019, 21: 40
1            03/05/2019, 21: 41  3828.5  3827.4       NaN       NaN                 NaN

I cannot figure out how to get this to stop appending to new columns instead of after the existing ones. If you can help thanks so much!

Upvotes: 0

Views: 1116

Answers (2)

vikas kumar
vikas kumar

Reputation: 54

In pandas dataframe columns appended by a series and row appended by a Dictionary( with exactly same columns name as key for dictionary)

Upvotes: 0

Alexis Winters
Alexis Winters

Reputation: 505

To append a row, append with a dictionary:

seriesMA = {'Time': datetime.now().strftime("%m/%d/%Y, %H: %M"), 'Fast MA:' : fastMA, 'Slow MA:' : slowMA}
    dfMA = dfMA.append(seriesMA, ignore_index=True)

Upvotes: 2

Related Questions