I have a pandas dataframe:
| items
--------------
0 | [a]
1 | [a, b]
2 | [d, e, f,f]
3 | [d, f, e]
4 | [c, a, b]
I would like to count the frequency of each item in the list and construct a table like the following:
a| b| c| d| e| f
-------------------------
0| 1| 0| 0| 0| 0| 0
1| 1| 1| 0| 0| 0| 0
2| 0| 0| 0| 1| 1| 2
3| 0| 0| 0| 1| 1| 1
4| 1| 1| 1| 0| 0| 0
I look at pandas.explode but I don't think that is what I want.
I can do something like this below. But I feel like there might be a more efficient way to do this. I have about 3.5 million rows.
import pandas as pd
from collections import Counter,defaultdict
df = pd.DataFrame({'items':[['a'],['a','b'],
['d','e','f','f'],['d','f','e'],
['c','a','b']]})
alist = sum(sum(df.values.tolist(),[]),[]) # flatten the list
unique_list = sorted(set(alist)) # get unique value for column names
unique_list
b = defaultdict(list)
for row in sum(df.values.tolist(),[]):
counts = Counter(row)
for name in unique_list:
if name in counts.keys():
b[name].append(counts[name])
else:
b[name].append(0)
pd.DataFrame(b)