Home > OS >  Insert values to a pandas column containing list alternatively from other column containing list
Insert values to a pandas column containing list alternatively from other column containing list

Time:07-02

Posting minimal reproducible example

Lets say I have a dataframe

            combined              values
0    [0, 0, 0, 0, 0, 0, 0, 0]     [1, 2, 3, 4]
1    [0, 0, 0, 0, 0, 0, 0, 0]     [5, 6, 7, 8] 
2             [0, 0, 0, 0, 0]     [9, 10, 11]

Now I need to populate column combined from column values such that, it is populated alternatively, like :

            combined              values
0    [1, 0, 2, 0, 3, 0, 4, 0]     [1, 2, 3, 4]
1    [5, 0, 6, 0, 7, 0, 8, 0]     [5, 6, 7, 8] 
2           [9, 0, 10, 0, 11]     [9, 10, 11]

It is guranteed that size of lists in combined will always be atleast 2 times the size of list in values.

I am looking for a solution more of slicing and inserting the values to the list, but that wouldn't work

df['combined'].str[::2] = df['values'].str[::]

P.S : There are numerous ways in which this can be achieved I am looking for a more pandaic approach

CodePudding user response:

Try:

for a, b in zip(df["combined"], df["values"]):
    a[::2] = b

print(df)

Prints:

                   combined        values
0  [1, 0, 2, 0, 3, 0, 4, 0]  [1, 2, 3, 4]
1  [5, 0, 6, 0, 7, 0, 8, 0]  [5, 6, 7, 8]
2         [9, 0, 10, 0, 11]   [9, 10, 11]

CodePudding user response:

This is not an efficient code but it will work for your case.

import pandas as pd

df = pd.DataFrame({'combined': [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0]],
                  'value':[[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11]]})

for i in range(len(df)):
    k = 0
    for j in range(len(df['combined'][i])):
        if (j % 2) == 0:
            df['combined'][i][j] = df['value'][i][k]
            k = k   1
print(df)

the output is

                   combined         value
0  [1, 0, 2, 0, 3, 0, 4, 0]  [1, 2, 3, 4]
1  [5, 0, 6, 0, 7, 0, 8, 0]  [5, 6, 7, 8]
2         [9, 0, 10, 0, 11]   [9, 10, 11]
  • Related