fredy kruger fredy kruger - 3 months ago 10
Python Question

Append a column to a 2 dimensional array

I have a 2d array in Python called "AllLines"

[['Suppliers', 'Spend', 'Test Field\n'],
['Dell Inc', '9000', '1\n'],
['Dell Computers', '9000', '2\n'],
['HBC Corp', '9000', '3\n'],
['HBC INC', '9000', '4']]


So, it is an array within an array. I need to append items to the inside array. To give me this:

[['NEW','Suppliers', 'Spend', 'Test Field\n'],
['N-E-W','Dell Inc', '9000', '1\n'],
['N-E-W---','Dell Computers', '9000', '2\n'],
['N-E---W','HBC Corp', '9000', '3\n'],
['N-W-W','HBC INC', '9000', '4']]


How do I achieve adding a new item to the inside arrays?

Answer

You can use a slice assignment:

>>> a = [['Suppliers', 'Spend', 'Test Field\n'], ['Dell Inc', '9000', '1\n']]
>>> a[0][0:0] = ["NEW"]
>>> a[1][0:0] = ["N-E-W"]
>>> a
[['NEW', 'Suppliers', 'Spend', 'Test Field\n'], ['N-E-W', 'Dell Inc', '9000', '1\n']]

Some timings:

>>> timeit.timeit(setup="a = [['Suppliers', 'Spend', 'Test Field'], ['Dell Inc', '9000', '1']]", 
    stmt="a[0][0:0] = ['NEW']", number=100000)
3.57850867468278
>>> timeit.timeit(setup="a = [['Suppliers', 'Spend', 'Test Field'], ['Dell Inc', '9000', '1']]", 
    stmt="a[0].insert(0, 'NEW')", number=100000)
4.941971139085055
>>> timeit.timeit(setup="a = [['Suppliers', 'Spend', 'Test Field'], ['Dell Inc', '9000', '1']]", 
    stmt="a[0] = ['NEW'] + a[0]", number=100000)
33.147023662906804