Home > Net >  Making Lists the same size
Making Lists the same size

Time:07-15

I have a list of lists that contains temperature data; however, sometimes a probe disconnects when I am trying to collect data and for example, pandas will complain:

ValueError: 5 columns passed, passed data had 4 columns

so if I have a list of list such as [[1, 2, 3], [1, 1, 1, 1, 1]] how can I make it such that the list becomes [[1, 2, 3, X, X], [1, 1, 1, 1, 1]] or if I had six sensors and the output was [[1, 1], [2, 2]] it becomes [[1, 1, X, X, X, X], [2, 2, X, X, X, X]].

In short, I would like to make each list the same size N and populate cells with an X

Edit: The fill will always occur at the end of the list

CodePudding user response:

You can simply add to your sublists the missing elements, for example:

NUMBER_OF_SENSORS = 6
data = [[1, 1], [2, 2]]

new_data = [l   ["X"] * (NUMBER_OF_SENSORS - len(l)) for l in data]

print(new_data)

Prints:

[[1, 1, "X", "X", "X", "X"], [2, 2, "X", "X", "X", "X"]]

CodePudding user response:

Bulkier but also more flexible solution

def fill (list_name, cap):
    while len (list_name) < cap:
        list_name.append ('x')
  • Related