Dataframe From List Of List
I have list of list u=[[1, 1], [2, 1, 1, 1], [2, 2, 1, 1, 1, 1, 2, 2], [2, 2, 2, 2, 2, 3, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2], [2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 3, 3, 3, 2, 2,
Solution 1:
You can use Counter
in order to transform list in to dictionary. Then using pd.DataFrame
to convert that dictionary
import pandas as pd
from collections importCounter
df = pd.DataFrame([Counter(u_) for u_ in u]).fillna(0)
note that there is no 4 in here, you can manually add it to dictionary or just add the 4 column in dataframe after i.e. df[4] = 0
Solution 2:
collections.Counter
is useful to do this:
First create Counter
instances from the lists and use these to instanciate DataFrames:
u=[[1, 1], [2, 1, 1, 1], [2, 2, 1, 1, 1, 1, 2, 2], [2, 2, 2, 2, 2, 3, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2], [2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 3, 3, 3, 2, 2, 3, 2, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2]]
from collections import Counter
import pandas as pd
df = pd.DataFrame([Counter(e) for e in u]).fillna(0)
df[4] = 0.0print(df)
Output
1 2 3 4
0 2 0.0 0.0 0.0
1 3 1.0 0.0 0.0
2 4 4.0 0.0 0.0
3 5 10.0 1.0 0.0
4 6 20.0 6.0 0.0
This is possible, because under the hood Counter
behaves like a dict
.
Post a Comment for "Dataframe From List Of List"