Roxanne
Roxanne

Reputation: 87

Replace every row in dataframe with a list

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

Upvotes: 2

Views: 658

Answers (3)

Corralien
Corralien

Reputation: 120391

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

Upvotes: 2

dp6000
dp6000

Reputation: 673

df[['A', 'B', 'C']] = df.D.tolist()

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

Upvotes: 0

Jordan Hyatt
Jordan Hyatt

Reputation: 434

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']]

Upvotes: 0

Related Questions