简体   繁体   中英

Appending individual items to lists in pandas Series

I am creating a Multiindexed pandas Series and each item is a list. First, an empty list, then I append each of these lists individually. However, when I tried to do that in a naive manner, I've faced a problem. It is easily duplicated in this simple example:

blah = pd.Series([[]]*8)
blah[0].append(30)
blah

What I wanted to get is this:

0    [30]
1    []
2    []
3    []
4    []
5    []
6    []
7    []

Instead the output is this:

0    [30]
1    [30]
2    [30]
3    [30]
4    [30]
5    [30]
6    [30]
7    [30]

Instead of appending one of the lists, it appends all of them with the same value.

My question: is this a bug or am I doing something wrong? Is there a better way of doing this?

(Please keep in mind that I am actually working with Multiindex Series, though I think it doesn't matter for this particular problem)

You should use something like [ [] for x in range(0,8) ]

This will create a new list ( [] ) 8 times instead of referencing 8 times the same list.

You could also find dictionaries useful.

lists = {}
for i in range(8):
    lists[i] = []

lists[0] = [30]

returns

{0: [30], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: []}

What if you append None instead.

foo = [None]*30
foo[0] = 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM