Multiply Rows And Append To Dataframe By Cell Value
Consider the following dataframe; df = pd.DataFrame( {'X':('a','b','c','d'), 'Y':('a','b','d','e'), 'Z':('a','b','c','d'), '#':(1,2,1,3)
Solution 1:
Use numpy.repeat
:
c = df.columns[1:]
df = pd.DataFrame(np.repeat(df.values, df['#'], axis=0)[:, 1:], columns=c)
print (df)
X Y Z
0 a a a
1 b b b
2 b b b
3 c d c
4 d e d
5 d e d
6 d e d
Similar:
df = pd.DataFrame(np.repeat(df.values, df['#'], axis=0), columns=df.columns)
print (df)
# X Y Z
0 1 a a a
1 2 b b b
2 2 b b b
3 1 c d c
4 3 d e d
5 3 d e d
6 3 d e d
But if order is important:
dfs = []
for i in range(df['#'].max()):
df = df[df['#'] > 0].copy()
df['#'] -= 1
dfs.append(df.iloc[:, 1:])
df1 = pd.concat(dfs, ignore_index=True)
print (df1)
X Y Z
0 a a a
1 b b b
2 c d c
3 d e d
4 b b b
5 d e d
6 d e d
Post a Comment for "Multiply Rows And Append To Dataframe By Cell Value"