Ben
Ben

Reputation: 23

Appending to a list inside a pandas dataframe

I have a pandas dataframe with a column of empty lists. I want to append to this list at a specific location within the dataframe. Below is the code I'm using.

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
                  index=['cobra', 'viper', 'sidewinder'],
                  columns=['max_speed', 'shield'])
df['new_col'] = [[]] * df.shape[0]
df.loc['viper', 'new_col'].append('a')

The ouput that I expect and want is:

            max_speed  shield new_col
cobra               1       2   []
viper               4       5   [a]
sidewinder          7       8   []

But the output that I am getting is:

            max_speed  shield new_col
cobra               1       2   [a]
viper               4       5   [a]
sidewinder          7       8   [a]

Why is this happening and how can I get my expected output? Thx

Upvotes: 1

Views: 166

Answers (1)

Ben
Ben

Reputation: 23

@Joylove answered this in the comments here.

All these lists are the same object. Setting one cell will set them all.

Using df['new_col'] = [[] for _ in range(df.shape[0])] will fix this.

Upvotes: 1

Related Questions