1

My dataframe is given below

df = 

index    data1
0         20
1         30
2         40

I want to add a new column and each element consiting a list.

My expected output is

df = 

index    data1    list_data
0         20       [200,300,90]
1         30       [200,300,90,78,90]
2         40       [1200,2300,390,89,78]

My present code:

        df['list_data'] = []
        df['list_data'].loc[0] = [200,300,90]

Present output:

    raise ValueError('Length of values does not match length of index')

ValueError: Length of values does not match length of index

2 Answers 2

2

You can use pd.Series for your problem

import pandas as pd
lis = [[200, 300, 90], [200, 300, 90, 78, 90], [1200, 2300, 390, 89, 78]]
lis = pd.Series(lis)
df['list_data'] = lis

This gives the following output

   index   data1    list_data
0   0        20    [200, 300, 90]
1   1        30    [200, 300, 90, 78, 90]
2   2        40    [1200, 2300, 390, 89, 78]
Sign up to request clarification or add additional context in comments.

Comments

1

Try using loc this way:

df['list_data'] = ''
df.loc[0, 'list_data'] = [200,300,90]

3 Comments

df['list_data'] = []' is this wrong? df['list_data'] = ""` is this correct? Because after correcting this, I got the answer.
Thanks. I added a new question at stackoverflow.com/questions/59997554/…
@Mainland Answered

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.