How to assign multiple columns to a series of list pandas

Viewed 37

I have a pandas dataframe as below:

           A  B      combined
        0  1  2      [1,2]
        1  2  3      [2,3]
        2  3  4      [3,4]
        3  4  5      [4,5]

I wanted to fill combined column from index 0 and 1 to 2 and 3 on columns A and B. The result looks like below:

           A  B      combined
        0  1  2      [1,2]
        1  2  3      [2,3]
        2  1  2      [3,4]
        3  2  3      [4,5]

What I tried:

df.loc[df.index.isin([2,3]), ['A','B']] = df.loc[df.index.isin([0,1]),'combined']

When I tried the above code the output is below.

            A   B      combined
        0   1   2        [1,2]
        1   2   3        [2,3]
        2  NAN  NAN      [3,4]
        3  NAN  NAN      [4,5]

Please advice. Please give me optimal solution as the real data I am dealing with is in millions.

Thank you in advance

1 Answers

You can try with tolist which remove the index align for dataframe assign

df.loc[df.index.isin([2,3]), ['A','B']] = \
       df.loc[df.index.isin([0,1]),'combined'].to_numpy().tolist()
Related