sds
sds

Reputation: 60004

How to create a sparse DataFrame from a list of dicts

I create DataFrame from a list of dicts like this:

pd.DataFrame([{"id":"a","v0":3,"v2":"foo"},
              {"id":"b","v1":1,"v4":"ouch"}]).set_index(
                 "id",verify_integrity=True)
     v0   v2   v1    v4
id                    
a   3.0  foo  NaN   NaN
b   NaN  NaN  1.0  ouch

Alas, for some inputs I run out of RAM in the DataFrame constructor, and I wonder if there is a way to make pandas produce a sparse DataFrame from the list of dicts.

Upvotes: 2

Views: 394

Answers (1)

mosc9575
mosc9575

Reputation: 6337

I suggest to use the dtype='Sparse' for this.

If all elements are numbers you can use dtype='Sparse', dtype='Sparse[int]' or dtype='Sparse[float]'

data = [{"id":'a',"v0":3,"v2":6},
        {"id":'b',"v1":1,"v4":7}]
index = [item.pop('id') for item in data]
pd.DataFrame(data, index=index, dtype="Sparse")

If any value is a string you have to use dtype='Sparse[str]'.

data = [{"id":'a',"v0":3,"v2":'foo'},
        {"id":'b',"v1":1,"v4":'ouch'}]
df = pd.DataFrame(data, dtype="Sparse[str]").set_index("id",verify_integrity=True)

Upvotes: 5

Related Questions