Mike S
Mike S

Reputation: 1603

Adding the same list to each row in a pandas DataFrame in a new column

In a pandas DataFrame, foo for example:

>>> foo
   col1  col2
0     1     0
1     2     0
2     3     1

If you want to add a new column, all with the same value you can do

>>> foo['col3'] = 1
>>> foo
   col1  col2  col3
0     1     0     1
1     2     0     1
2     3     1     1

If you want to add another new column, all with specific values you can do

>>> foo['col4'] = ['a', 'b', 'c']
>>> foo
   col1  col2  col3  col4
0     1     0     1     a
1     2     0     1     b
2     3     1     1     c

But what I want to do is add the same list to each row as new column. Something like

>>> myList = [True, False, False, True]
>>> foo['col5'] = {...something something something...}
>>> foo
   col1  col2  col3  col4                        col5
0     1     0     1     a  [True, False, False, True]
1     2     0     1     b  [True, False, False, True]
2     3     1     1     c  [True, False, False, True]

Using the previous method results in ValueError('Length of values does not match length of ' 'index'). So at the moment, my {...something something something...} line is foo['col5'] = [myList] * foo.shape[0]. But I'm wondering, is there a better way?

Upvotes: 3

Views: 2708

Answers (1)

cs95
cs95

Reputation: 402493

Use a list comprehension.

v = [True, False, False, True]
df['col5'] = [v for _ in range(len(df))]

df
   col1  col2                        col5
0     1     0  [True, False, False, True]
1     2     0  [True, False, False, True]
2     3     1  [True, False, False, True]

You might be tempted to use

df['col5'] = [True, False, False, True] * len(df)

However, each record actually references the same list. Try this -

df.loc[0, 'col5'][0] = False
df

   col1  col2                         col5
0     1     0  [False, False, False, True]
1     2     0  [False, False, False, True]
2     3     1  [False, False, False, True]

You'll see the change is reflected across all sublists.

Upvotes: 8

Related Questions