Home > Enterprise >  How to insert another column values in a column with their respective location?
How to insert another column values in a column with their respective location?

Time:09-16

enter image description here

a=data["Col2"]
a=a.dropna()
a=pd.DataFrame(a)
k=[]
for i in data["Col1"]:
  k.append(i)
o=1
for i in a.index:
  o=o i
  k.insert(o,a['COLOR2'][i])
  o =1 

But the problem here is the index of Col1 changes after 1st insertion. And after adding 1(o =1), it still does not give the desired output.

CodePudding user response:

If need new one column DataFrame from columns Col1, Col2 use:

df = data[['Col1','Col2']].stack().reset_index(drop=True).to_frame('Col')

CodePudding user response:

Use a counter initialized to 1, such as -

a=data["Col2"]
a=a.dropna()
a=pd.DataFrame(a)
k=[]
for i in data["Col1"]:
  k.append(i)

counter=1

for i in a.index:
  o=i counter
  k.insert(o,a['Col2'][i])

  counter =1
  • Related