How do I expand my pands dataframe through a loop?

Question:

So I have a table like this in my pandas dataframe

# A B
0 f 1
1 g 2

But idk what code to write to transform it to

# A B
0 f 1a
1 f 1b
2 g 2a
3 g 2b
Asked By: van dam

||

Answers:

Assuming you want a cross product:

import numpy as np
import pandas as pd

df = pd.DataFrame({'#': [0, 1], 'A': list('fg'), 'B': [1, 2]})

l = ['a', 'b']

out = (
 df.loc[df.index.repeat(len(l))]
   .assign(**{'B': lambda d: d['B'].astype(str)+np.tile(l, len(df)),
              '#': lambda d: range(len(d))})
 ) 

Or with a cross merge:

out = (
 df.merge(pd.Series(l, name='tmp'), how='cross')
   .assign(**{'B': lambda d: d['B'].astype(str)+d.pop('tmp'),
              '#': lambda d: range(len(d))})
)

Output:


   #  A   B
0  0  f  1a
0  1  f  1b
1  2  g  2a
1  3  g  2b
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.