2

I have a dataframe with a column containing a list with values to replace each column, and I'm not sure how to move the list to do this. Here is an example dataframe:

            A    B    C    D
2020-07-31  0    0    0    [2,3,4]
2020-08-31  0    0    0    [5,6,7]
2020-09-30  0    0    0    [8,9,10]
2020-10-31  0    0    0    [0,1,2]

I would want to replace column A, B, and C with D like so:

            A    B    C    
2020-07-31  2    3    4  
2020-08-31  5    6    7 
2020-09-30  8    9    10 
2020-10-31  0    1    2   

What is the most efficient way to do this?

EDIT: column D is in the original dataframe, I want to move the values from D into A, B, and C and then drop the column D

Roxanne
  • 77
  • 4
  • Please refer to this already answered question: https://stackoverflow.com/questions/35491274/split-a-pandas-column-of-lists-into-multiple-columns – dp6000 Jul 21 '22 at 20:16

3 Answers3

2

You can use:

df[:] = df.pop('D').to_list()
# or specifying columns
# df[['A', 'B', 'C']] = df.pop('D').tolist()

print(df)

# Output
            A  B   C
2020-07-31  2  3   4
2020-08-31  5  6   7
2020-09-30  8  9  10
2020-10-31  0  1   2
mozway
  • 194,879
  • 13
  • 39
  • 75
Corralien
  • 109,409
  • 8
  • 28
  • 52
0

Assuming col "D" is not already in the original dataset and those dates are the index

df['D'] = df.apply(lambda ser: list(ser), axis=1)

If you only want to keep the index and column D

df = df[['D']]
Jordan Hyatt
  • 435
  • 3
  • 7
0
df[['A', 'B', 'C']] = df.D.tolist()

The proposed solution assumes that Column D will always have a list with exact three items.

dp6000
  • 473
  • 5
  • 15