处理/转置Pandas数据框架

3

I got the following pandas dataframe:

Id    Category
1     type 2
1     type 3
1     type 2
2     type 1
2     type 2

我需要处理和转置上述数据帧为:
Id Category_type_1 Category_type_2 Category_type_3
1          0               2              1
2          1               1              0

如果有人能够展示在Python中编写此代码的最简单方法,将不胜感激。

3个回答

3
pd.crosstab(df['Id'], df['Category'])
Out: 
Category  type 1  type 2  type 3
Id                              
1              0       2       1
2              1       1       0

3

我建议使用groupbysize函数

df.groupby(df.columns.tolist()).size().unstack().fillna(0)

enter image description here


看起来你的解决方案是最快的 ;) - jezrael
感谢大家的解决方案!看起来这个答案是最简单的.. :) - iLoeng

2
使用 pivot_table 函数:
print (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0))
Category  type 1  type 2  type 3
Id                              
1              0       2       1
2              1       1       0

时间:

小型数据集 - len(df)=5:

In [63]: %timeit df.groupby(df.columns.tolist()).size().unstack().fillna(0)
1000 loops, best of 3: 1.33 ms per loop

In [64]: %timeit (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0))
100 loops, best of 3: 3.77 ms per loop

In [65]: %timeit pd.crosstab(df['Id'], df['Category'])
100 loops, best of 3: 4.82 ms per loop

大型数据框 - len(df)=5k:

df = pd.concat([df]*1000).reset_index(drop=True)

In [59]: %timeit df.groupby(df.columns.tolist()).size().unstack().fillna(0)
1000 loops, best of 3: 1.73 ms per loop

In [60]: %timeit (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0))
100 loops, best of 3: 4.64 ms per loop

In [61]: %timeit pd.crosstab(df['Id'], df['Category'])
100 loops, best of 3: 5.46 ms per loop

非常大的数据框 - len(df)=5m:

df = pd.concat([df]*1000000).reset_index(drop=True)

In [55]: %timeit df.groupby(df.columns.tolist()).size().unstack().fillna(0)
1 loop, best of 3: 514 ms per loop

In [56]: %timeit (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0))
1 loop, best of 3: 907 ms per loop

In [57]: %timeit pd.crosstab(df['Id'], df['Category'])
1 loop, best of 3: 822 ms per loop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接