# Python pandas: Take column of counts and create DataFrame with a row per count

I have a DataFrame with values in columns a and b and a third column with the count of that row. I would like to convert this into a DataFrame (either new or remake the old one) with columns a and b repeated the number of times as is in the count column. It's probably more clear with an example. I have this DataFrame:

import pandas as pd
df = pd.DataFrame({'a' : [1,2,3], 'b' : [0,0,1], 'count' : [3,1,4]})


I am converting it like this:

new_df = pd.DataFrame(columns=df.columns[:-1])
for _, row in df.iterrows():
num = row['count']
for i in range(num):
pd.concat([new_df, row])
new_df = new_df.append(row[:-1])


This does exactly what I want but seems inelegant to me because of the for-loop inside iterrows. Is there a better or more pythonic way to do this?

You are correct in thinking that iterrows is a very bad sign for Pandas code. Even worse is building up a DataFrame one row at a time like this with pd.concat - the performance implications are dreadful.

Instead of reaching for loops, your first step should be to check if there is a vectorized DataFrame method you could use. In this case.. perhaps there isn't.

Next step is dropping into NumPy. And lo and behold, there is numpy.repeat, which allows you to repeat an array along an axis with another array of counts. We can wrap that up in a function.

def repeat_frame(df, counts):
rep_array = np.repeat(df.values, counts, axis=0)
return pd.DataFrame(rep_array, columns=df.columns)

# would be called with
repeat_frame(df[['a', 'b']], df['count'])


This runs in 450 µs on my machine compared to your current solution in 20.2 ms for your sample data. On a larger sample size with 1000 rows, it runs in 511 µs compared to 6.86 s for your current solution, roughly 13000 times faster.

If you find yourself wanting to use pd.concat or similar in any situation like this to build up a DataFrame row-by-row, stop! There is going to be a faster way.

And if you are certain you have some wild iteration logic that cannot be vectorized (which is unlikely), create an empty array of the necessary shape and consider using Numba or Cython to speed up filling it up with a loop.
{"ft_lang_label":"__label__en","ft_lang_prob":0.84827626,"math_prob":0.86718667,"size":760,"snap":"2022-27-2022-33","text_gpt3_token_len":207,"char_repetition_ratio":0.12698413,"word_repetition_ratio":0.0,"special_character_ratio":0.29605263,"punctuation_ratio":0.16853933,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9837108,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-08-09T01:28:44Z\",\"WARC-Record-ID\":\"<urn:uuid:7dbc94ff-b8c7-439a-90c1-ec257f034549>\",\"Content-Length\":\"221267\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:5d9da7df-2a58-4c5d-8685-e9240cd16b64>\",\"WARC-Concurrent-To\":\"<urn:uuid:6e94dc70-5fe3-40bc-8724-5be4239ecfe8>\",\"WARC-IP-Address\":\"151.101.193.69\",\"WARC-Target-URI\":\"https://codereview.stackexchange.com/questions/200945/python-pandas-take-column-of-counts-and-create-dataframe-with-a-row-per-count\",\"WARC-Payload-Digest\":\"sha1:IFXS65QFHVG4X5GZV6KIQVRFWEODBQAW\",\"WARC-Block-Digest\":\"sha1:D67NHVXNPN2FW6YDCLBNLI4BITU3AS76\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-33/CC-MAIN-2022-33_segments_1659882570879.37_warc_CC-MAIN-20220809003642-20220809033642-00732.warc.gz\"}"}