3

I have two arrays. column_names hold the column titles. values hold all the values.

I understand if I do this:

column_names = ["a", "b", "c"]
values = [1, 2, 3]
for n, v in zip(column_names, values):
    print("{} = {}".format(n, v))

I get

a = 1
b = 2
c = 3

How do I code it so if I pass:

column_names = ["a", "b", "c"]
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]

I would get

a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

Thank you!

0

5 Answers 5

5

With pandas and numpy it is easy and the result will be a much more useful table. Pandas excels at arranging tabular data. So lets take advantage of it: install pandas with:

pip install pandas --user
#pandas comes with numpy
import numpy as np
import pandas as pd

# this makes a normal python list for integers 1-9
input = list(range(1,10))

#lets convert that to numpy array as np.array
num = np.array(input)

#currently its shape is single dimensional, lets change that to a two dimensional matrix that turns it into the clean breaks you want
reshaped = num.reshape(3,3)

#now construct a beautiful table
pd.DataFrame(reshaped, columns=['a','b','c'])

#ouput is
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it as follows

>>> for n, v in zip(column_names, zip(*[values[i:i+3] for i in range(0,len(values),3)])):
...     print("{} = {}".format(n, ', '.join(map(str, v))))
... 
a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

Alternatively, you can use grouper defined in itertools

>>> def grouper(iterable, n, fillvalue=None):
...     "Collect data into fixed-length chunks or blocks"
...     # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
...     args = [iter(iterable)] * n
...     return zip_longest(*args, fillvalue=fillvalue)
... 
>>> from itertools import zip_longest
>>> for n, v in zip(column_names, zip(*grouper(values, 3))):
...     print("{} = {}".format(n, ', '.join(map(str, v))))
... 
a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

Comments

1

itertools.cycle seems appropriate in this case. Here's another version for future readers:

import itertools

column_names = ["a", "b", "c"]
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]

L = zip(itertools.cycle(column_names), values)

for g, v in itertools.groupby(sorted(L), lambda x: x[0]):
    print("{} = {}".format(g, [i[1] for i in v]))

gives:

a = [1, 4, 7]
b = [2, 5, 8]
c = [3, 6, 9]

Comments

0

This has two sub-steps that you want to do.

First, you want to divide your list into chunks, and then you want to assign those chunks to a dictionary.

To split the list into chunks, we can create a function:

def chunk(values, chunk_size):
    assert len(values)%chunk_size == 0 # Our chunk size has to evenly fit in our list
    steps = len(values)/chunk_size
    chunky_list = []
    for i in range(0,steps):
        position = 0 + i
        sub_list = []
        while position < len(values):
            sub_list.append(values[position])
            position += chunk_size
        chunky_list.append(sub_list)
    return chunky_list

At this point we will have: [[1,4,7],[2,5,8],[3,6,9]]

From here, creating the dict is really easy. First, we zip the two lists together:

zip(column_names, chunk(3))

And take advantage of the fact that Python knows how to convert a list of tuples into a dictionary:

dict(zip(column_names, chunk(3)))

Comments

0

You can also use slicing and a collections.defaultdict to collect your values:

from collections import defaultdict

column_names = ["a", "b", "c"]
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]

column_len = len(column_names)

d = defaultdict(list)
for i in range(0, len(values), column_len):
    seq = values[i:i+column_len]

    for idx, number in enumerate(seq):
        d[column_names[idx]].append(number)

for k, v in d.items():
    print('%s = %s' % (k, ', '.join(map(str, v))))

Which Outputs:

a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

This can be imporoved if you create zipped lists with itertools.cycle, avoiding the slicing all together:

from collections import defaultdict
from itertools import cycle

column_names = ["a", "b", "c"]
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]

column_names = cycle(column_names)

d = defaultdict(list)
for column, val in zip(column_names, values):
    d[column].append(val)

for k, v in d.items():
    print('%s = %s' % (k, ', '.join(map(str, v))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.