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?