Shubzumt
Shubzumt

Reputation: 143

Expand pandas dataframe by replacing cell value with a list

I have a pandas dataframe like this below:

A B C
a b c
d e f

where A B and C are column names. Now i have a list:

mylist = [1,2,3]

I want to replace the c in column C with list such as dataframe expands for all value of list, like below:

A B C
a b 1
a b 2
a b 3
d e f

Any help would be appreciated!

Upvotes: 1

Views: 479

Answers (2)

jezrael
jezrael

Reputation: 862731

You can use:

print (df)
   A  B  C
0  a  b  c
1  d  e  f
2  a  b  c
3  t  e  w
mylist = [1,2,3]

idx1 = df.index[df.C == 'c']
df = df.loc[idx1.repeat(len(mylist))].assign(C=mylist * len(idx1)).append(df[df.C != 'c'])
print (df)
   A  B  C
0  a  b  1
0  a  b  2
0  a  b  3
2  a  b  1
2  a  b  2
2  a  b  3
1  d  e  f
3  t  e  w

Upvotes: 1

Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

I tried this,

mylist = [1,2,3]
x=pd.DataFrame({'mylist':mylist})
x['C']='c'
res= pd.merge(df,x,on=['C'],how='left')
res['mylist']=res['mylist'].fillna(res['C'])

For further,

del res['C']
res.rename(columns={"mylist":"C"},inplace=True)
print res

Output:

   A  B  C
0  a  b  1
1  a  b  2
2  a  b  3
3  d  e  f

Upvotes: 2

Related Questions