Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a matrix from dynamic dictionary

I want to create a matrix.

Input:

data = [
    {'a': 2, 'g': 1},
    {'p': 3, 'a': 5, 'cat': 4}
    ...
]

Output:

     a  p  cat  g
1st  2  0  0    1
2nd  5  3  4    0

This is my code. But I think it's not smart and very slow when data size huge.

Have any good ways to do this one?

Thank you.

data = [
    {'a': 2, 'g': 1},
    {'p': 3, 'a': 5, 'cat': 4}
]

### Get keyword map ###
key_map = set()
for row in data:
    key_map = key_map.union(set(row.keys()))

key_map = list(key_map)    # ['a', 'p', 'g', 'cat']

### Create matrix ###
result = []
for row in data:
    matrix = [0] * len(key_map)
    for k, v in row.iteritems():
        matrix[key_map.index(k)] = v
    result.append(matrix)

print result        

# [[2, 0, 0, 1], [5, 3, 4, 0]]

Edited

By @wwii advice. Use Pandas looks good:

from pandas import DataFrame

result = DataFrame(data, index=range(len(data)))
print result.fillna(0, downcast=int).as_matrix().tolist()
# [[2, 0, 1, 0], [5, 4, 0, 3]]
like image 872
Puffin GDI Avatar asked Sep 14 '26 19:09

Puffin GDI


1 Answers

You can use set comprehension to generate the key_map

key_map = list({data for row in data for data in row})
like image 154
thefourtheye Avatar answered Sep 16 '26 10:09

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!