1

I have a function which returns a list of lists and I'd like to add multiple columns to my dataframe based on the return value. Here is how the return value of my function looks like

[[1,2,3],[3,4,3],[1,6,7],[4,7,6]]

I would like to add three columns to my dataframe. I have the following code

 col_names = ['A','B','C']
 df[col_names] = func()

but it gives me an error. How can I add 3 new columns?

2
  • What is the error? What should the output columns look like? Which list elements go into which columns? Commented Feb 12, 2019 at 18:55
  • each sublist would be one row Commented Feb 12, 2019 at 18:56

3 Answers 3

2

you can pass the list directly:

pd.DataFrame([[1,2,3],[3,4,3],[1,6,7],[4,7,6]],columns=['A','B','C'])

   A  B  C
0  1  2  3
1  3  4  3
2  1  6  7
3  4  7  6

Or if you have defined the list as l = [[1,2,3],[3,4,3],[1,6,7],[4,7,6]], pass it to the Dataframe:

df = pd.Dataframe(l,columns=['A','B','C'])
Sign up to request clarification or add additional context in comments.

3 Comments

this is different than what I want. I want to append a bunch of new columns to my existing dataframe
can you show your function , a sample df and what you want to achieve?
@H.Z. simply do this, then concat it onto your existing dataframe, or merge if you need to do it on key columns
0

Here is one way to do it:

df = pd.DataFrame({'foo': ['bar', 'buzz', 'fizz']})

def buzz():
    return [[1,2,3],[3,4,3],[1,6,7],[4,7,6]]


pd.concat([df, pd.DataFrame.from_records(buzz(), columns=col_names)], axis=1)

    foo  A  B  C
0   bar  1  2  3
1  buzz  3  4  3
2  fizz  1  6  7
3   NaN  4  7  6 

2 Comments

in my case df has 865 record and the new dataframe also has the same number of records, so I expect the resulting dataframe to have 865 records as well. but it has around 1600 records!
does the function that returns data return 865 lists with 3 items each?
0

Here is an example with a dummy function that returns a list of list. Since the function returns a list, you need to pass it to pd.DataFrame constructor before assigning it to the existing dataframe.

def fn(l1,l2,l3):
    return [l1,l2,l3]
df = pd.DataFrame({'col': ['a', 'b', 'c']})
col_names = ['A','B','C']
df[col_names] = pd.DataFrame(fn([1,2,3], [3,4,3], [4,7,6]))

You get

    col A   B   C
0   a   1   2   3
1   b   3   4   3
2   c   4   7   6

2 Comments

for some reason, when I do that all the new added columns (A,B, C) would have only Null
What does your function look like? I created a dummy function that returns list of lists. You need to replace fn(...) with your function

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.