[英]How to convert a dictionary with list values into dataframe showing the counts of values of dictionary
I have a dictionary like this:我有一本这样的字典:
Dictionary:
{1:['A','B','B','C'],
2:['A','B','C','D','D','E','E','E','E'],
3:['C','C','C','D','D','D','D']
}
I want to convert this dictionary into a data frame that has keys on the index and its list values on columns and display the count of the list values like this:我想将此字典转换为在索引上具有键并在列上具有列表值的数据框,并显示列表值的计数,如下所示:
DataFrame:
A B C D E
1 1 2 1 0 0
2 1 1 1 2 4
3 0 0 3 4 0
Please help me with how I can achieve this data frame!请帮助我如何实现这个数据框!
You can utilize Counter
here:您可以在此处使用Counter
:
from collections import Counter
import pandas as pd
d = {1:['A','B','B','C'],
2:['A','B','C','D','D','E','E','E','E'],
3:['C','C','C','D','D','D','D']
}
count_dict = {k: Counter(v) for k, v in d.items()}
res = pd.DataFrame.from_dict(count_dict, orient='index').fillna(0).astype('int')
print(res)
# A B C D E
# 1 1 2 1 0 0
# 2 1 1 1 2 4
# 3 0 0 3 4 0
You can do it like this also:你也可以这样做:
pd.DataFrame.from_dict(d, orient='index').T.apply(pd.Series.value_counts).T.fillna(0)
Output:输出:
A B C D E
1 1.0 2.0 1.0 0.0 0.0
2 1.0 1.0 1.0 2.0 4.0
3 0.0 0.0 3.0 4.0 0.0
Let us try explode
with pd.crosstab
让我们尝试使用pd.crosstab
explode
s = pd.Series(d).explode()
out = pd.crosstab(s.index,s)
Out[257]:
col_0 A B C D E
row_0
1 1 2 1 0 0
2 1 1 1 2 4
3 0 0 3 4 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.