0

I am trying to append a list looking like this

myList = ['2018-01-12', 'MMM', 'BUY', 42, 236.5229]

to an empty dataframe (with "header" / columns names).

To create the dataframe I've done the following:

tradeLog = pd.DataFrame(columns=["DATE", "TICKER", "ORDER_TYPE", "AMOUNT", "PRICE"])

I am trying to append the list as a row in the following way:

tradeLog.append(myList, ignore_index=True)

(NOTICE: My goal i to iterate over some data - a lot of lists in the same format - and the add them one by one to the dataframe)

2
  • tradeLog.loc[len(tradeLog)] = my_list Commented Apr 20, 2019 at 21:00
  • This works very well - thank you Commented Apr 20, 2019 at 21:02

2 Answers 2

1

The pandas documentation reads

DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)

other : DataFrame or Series/dict-like object, or list of these The data to append.

So you need to have to transform your list prior to appending it to your DataFrame:

something that might work is to zip the list of your columns to the content of your myList so it would be:

tradeLog = pd.DataFrame(columns=["DATE", "TICKER", "ORDER_TYPE", "AMOUNT", "PRICE"])
myList = ['2018-01-12', 'MMM', 'BUY', 42, 236.5229]
myDict = dict(zip(tradeLog.columns.tolist(), myList))

tradeLog.append(myDict, ignore_index=True)

or tradeLog.append(pd.DataFrame(myDict), ignore_index=True)

This being said you need to ensure your lists are always the same length as your columns names list.

Sign up to request clarification or add additional context in comments.

Comments

0

DataFrame.append() is for appending rows from an other pandas dataframe or series (see the docs).

So, if it is absolutely necessary to do this line by line, you can

tradeLog = tradeLog.append(pd.Series(myList, index=tradeLog.columns), ignore_index=True)

(N.b.: tradeLog.loc[len(tradeLog)] = ... appends to the end only as long as you have a simple integer index on tradeLog, but might break for more complex use cases.)

You might also want to consider this remark from the docs:

Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.