From this question and others it seems that it is not recommended to use concat
or append
to build a pandas dataframe because it is recopying the whole dataframe each time.
My project involves retrieving a small amount of data every 30 seconds. This might run for a 3 day weekend, so someone could easily expect over 8000 rows to be created one row at a time. What would be the most efficient way to add rows to this dataframe?
sundance's answer might be correct in terms of usage, but the benchmark is just wrong. As moobie correctly pointed out an index 3 already exists in this example, which makes access way quicker than with a non-existent index. Have a look at this:
2.15 s ± 88 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
972 ms ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
1.13 s ± 46 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Of course, this is purely synthetic, and I admittedly wasn't expecting these results, but it seems that with non-existent indices
.loc
and.append
perform quite similarly. Just leaving this here.Editing the chosen answer here since it was completely mistaken. What follows is an explanation of why you should not use setting with enlargement. "Setting with enlargement" is actually worse than append.
The tl;dr here is that there is no efficient way to do this with a DataFrame, so if you need speed you should use another data structure instead. See other answers for better solutions.
More on setting with enlargement
You can add rows to a DataFrame in-place using
loc
on a non-existent index, but that also performs a copy of all of the data (see this discussion). Here's how it would look, from the Pandas documentation:For something like the use case described, setting with enlargement actually takes 50% longer than
append
:With
append()
, 8000 rows took 6.59s (0.8ms per row)With
.loc()
, 8000 rows took 10s (1.25ms per row)What about a longer DataFrame?
As with all profiling in data-oriented code, YMMV and you should test this for your use case. One characteristic of the copy-on-write behavior of
append
and "setting with enlargement" is that it will get slower and slower with largeDataFrame
s:Building a 16k row
DataFrame
with this method takes 2.3x longer than 8k rows.Assuming that your dataframe is indexed in order you can:
First check to see what the next index value is to create a new row:
Then use 'at' to write to each desired column
You need to split the problem into two parts:
If your data is critical (that is, you cannot afford to lose it) - send it to a queue and then read it from the queue in batches.
The queue will provide reliable (guaranteed) acceptance and that your data will not be lost.
You can read the data from the queue and dump it in a database.
Now your Python app simply reads from the database and does the analysis at whatever interval makes sense for the application - perhaps you want to do hourly averages; in this case you would run your script each hour to pull the data from the db and perhaps write the results in another database / table / file.
The bottom line - split the collecting and analyzing parts of your application.
I used this answer's
df.loc[i] = [new_data]
suggestion, but I have > 500,000 rows and that was very slow.While the answers given are good for the OP's question, I found it more efficient, when dealing with large numbers of rows up front (instead of the tricking in described by the OP) to use csvwriter to add data to an in memory CSV object, then finally use
pandas.read_csv(csv)
to generate the desired DataFrame output.This, for ~500,000 rows was 1000x faster and as the row count grows the speed improvement will only get larger (
the df.loc[1] = [data]
will get a lot slower comparatively)Hope this helps someone who need efficiency when dealing with more rows than the OP.
The response of Tom Harvey works well. However, I would like to add an simpler answer based on pandas.DataFrame.from_dict.
By adding the data of a row in a list and then this list to a dictionary, you can then use
pd.DataFrame.from_dict(dict)
to create a dataframe without iteration.If each value of the dictionary is a row. You can use just:
pd.DataFrame.from_dict(dictionary,orient='index')
Small example: