Skip to main content
 首页 » 编程设计

python之以适合创建图表的格式对 Pandas 数据框进行分组

2024年10月17日9lovecherry

假设我有以下 pandas 数据框:

In [1]: df 
Out[1]: 
  sentiment        date 
0       pos  2016-10-08 
1       neu  2016-10-08 
2       pos  2016-10-09 
3       neg  2016-10-09 
4       neg  2016-10-09 

我确实可以创建一个数据框,对每天的情绪列进行汇总统计,如下所示:

gf=df.groupby(["date", "sentiment"]).size().reset_index(name='count') 

给出

In [2]: gf 
Out[2]: 
         date sentiment  count 
0  2016-10-08       neu      1 
1  2016-10-08       pos      1 
2  2016-10-09       neg      2 
3  2016-10-09       pos      1 

但是我需要将此结果转换为以下表格格式(或新数据框),以便能够制作条形图(例如 this Google 条形图)。

  date        pos neg neu   
0  2016-10-08 1    0   1       
1  2016-10-09 1    2   0     

我试图通过创建一个新的数据框来解决这个问题

columns = ['date','pos', 'neg', 'neu'] 
 
clean_sheet = pd.DataFrame(columns=columns) 

然后遍历 gf寻找独特的日期,然后迭代那些使用 .loc 搜索 pos、neg 或 neu 的日期但它真的很乱

对于更简单的解决方案有什么想法吗?

谢谢

请您参考如下方法:

您需要添加 unstack :

gf = df.groupby(["date", "sentiment"]).size().unstack(fill_value=0).reset_index() 
#remove column name 'sentiment' 
gf.columns.name = None 
print (gf) 
         date  neg  neu  pos 
0  2016-10-08    0    1    1 
1  2016-10-09    2    0    1 

另一个较慢的解决方案 pivot_table :

gf = df.pivot_table(index="date", columns="sentiment", aggfunc=len, fill_value=0) 
       .reset_index() 
gf.columns.name = None 
print (gf) 
         date  neg  neu  pos 
0  2016-10-08    0    1    1 
1  2016-10-09    2    0    1 

最后一个解决方案是 crosstab ,但在较大的 DataFrame 中速度较慢:

gf = pd.crosstab( df.date, df.sentiment).reset_index() 
gf.columns.name = None 
print (gf) 
         date  neg  neu  pos 
0  2016-10-08    0    1    1 
1  2016-10-09    2    0    1 

时间( Pandas 0.19.0):

#[50000 rows x 2 columns] 
df = pd.concat([df]*10000).reset_index(drop=True) 
 
In [197]: %timeit (df.groupby(["date", "sentiment"]).size().unstack(fill_value=0).reset_index()) 
100 loops, best of 3: 6.3 ms per loop 
 
In [198]: %timeit (df.pivot_table(index="date", columns="sentiment", aggfunc=len, fill_value=0).reset_index()) 
100 loops, best of 3: 12.2 ms per loop 
 
In [199]: %timeit (pd.crosstab( df.date, df.sentiment).reset_index()) 
100 loops, best of 3: 11.3 ms per loop