我有一个类似于以下内容的数据框
+----------------+-------+
| class | year |
+----------------+-------+
| ['A', 'B'] | 2001 |
| ['A'] | 2002 |
| ['B'] | 2001 |
| ['A', 'B', 'C']| 2003 |
| ['B', 'C'] | 2001 |
| ['C'] | 2003 |
+----------------+-------+
我想以此创建一个数据框,以使结果表显示每个类中每个类别的计数。
+-----+----+----+----+
|year | A | B | C |
+-----+----+----+----+
|2001 | 1 | 3 | 1 |
|2002 | 1 | 0 | 0 |
|2003 | 1 | 1 | 2 |
+-----+----+----+----+
最简单的方法是什么?
答案 0 :(得分:5)
s=unnesting(df,['class'])
然后,我们做crosstab
pd.crosstab(s['year'],s['class'])
sklearn
的方法
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
pd.DataFrame(mlb.fit_transform(df['class']),columns=mlb.classes_, index=df.year).sum(level=0)
Out[293]:
A B C
year
2001 2 2 1
2002 1 1 1
2003 0 1 1
get_dummies
的方法
df.set_index('year')['class'].apply(','.join).str.get_dummies(sep=',').sum(level=0)
Out[297]:
A B C
year
2001 2 2 1
2002 1 1 1
2003 0 1 1
def unnesting(df, explode):
idx = df.index.repeat(df[explode[0]].str.len())
df1 = pd.concat([
pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
df1.index = idx
return df1.join(df.drop(explode, 1), how='left')