HHH
HHH

Reputation: 6485

How to add multiple column to a dataframe

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?

Upvotes: 1

Views: 101

Answers (3)

Vaishali
Vaishali

Reputation: 38415

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

Upvotes: 0

gold_cy
gold_cy

Reputation: 14236

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 

Upvotes: 0

anky
anky

Reputation: 75130

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

Upvotes: 2

Related Questions