Home > Back-end >  Copy elements at a given position in another position pandas df
Copy elements at a given position in another position pandas df

Time:06-15

I have a df:

num   mut
 67    O
 68    T
 69    D
   ...

I want to copy the second and third and so on element of the mut column into the first row, obtaining

num   mut
67    OTD...
68    T
69    D
  ...

How can I do it? Is it possible?

CodePudding user response:

IIUC, you can try

df['mut'].iloc[0] = ''.join(df['mut'])
# or
df.loc[0, 'mut'] = ''.join(df['mut'])
print(df)

   num  mut
0   67  OTD
1   68    T
2   69    D

CodePudding user response:

My answer is very similar to Ynjxsjmh. The difference is, instead of 2 & 3 row, you can make this code more dynamic.

df = pd.DataFrame({'num': [67, 68, 69],
                    'mut': ['O', 'T', 'D']})

You can use multiple row or different columns or also create a loop

x = df.iloc[1]['mut']
y = df.iloc[2]['mut']

val = ''.join([df.iloc[0]['mut'], x, y])

Update the relevant cell

df.iloc[0, 1] = val
print(df)
  • Related