简体   繁体   中英

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 .

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

If all elements are numbers you can use dytpe='Sparse' , dytpe='Sparse[int]' or dytpe='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 dytpe='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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM