How to repeat cells in a pandas DataFrame
2 answers
np.tile
and np.repeat
pd.DataFrame(dict(
name=np.tile(df.name.values, 2),
number=np.repeat(df.number.values, 2)
))
name number
0 a 2
1 b 2
2 a 1
3 b 1
pd.MultiIndex.from_product
pd.DataFrame(
pd.MultiIndex.from_product(
[df.name.unique(), df.number.unique()]
).values.tolist(), columns=df.columns)
name number
0 a 2
1 b 2
2 a 1
3 b 1
+4
source to share
repeated lines:
In [10]: pd.concat([df] * 2, ignore_index=True)
Out[10]:
name number
0 a 2
1 b 1
2 a 2
3 b 1
Cartesian product of column values:
In [14]: from itertools import product
In [15]: pd.DataFrame(list(product(df.name, df.number)), columns=df.columns)
Out[15]:
name number
0 a 2
1 a 1
2 b 2
3 b 1
+3
source to share