Last active
August 3, 2016 14:25
-
-
Save janpipek/e14c6b8121607e59a60a803df6adeb1e to your computer and use it in GitHub Desktop.
Make multiple copies of each row
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def multiply_rows(df, n, group=True): | |
"""Make multiple copies of each row in pandas. | |
:param df: the dataframe | |
:param n: how many copies | |
:param group: whether to group copies next to each other (AABB) or not (ABAB) | |
""" | |
new_df = pd.DataFrame() | |
for col in df: | |
series = df[col] | |
if group: | |
new_df[col] = np.broadcast_to(series, (n,) + series.shape).T.flatten() | |
else: | |
new_df[col] = np.broadcast_to(series, (n,) + series.shape).flatten() | |
return new_df |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment