漂亮打印Pandas DataFrame groupby

时间:2014-01-22 10:10:23

标签: pandas

是否有简单的方法来漂亮地打印pandas.DataFrame.groupby.count()结果?

我的代码是:

print out_df.groupby(['Symbol','Account'])['OrderID'].count()

我的输出是:

Symbol  Account 
XXXXX   123    34
        124    32
YYYYY   123    22
        124    24
dtype: int64

我想:

Symbol  Account Count
XXXXX   123     34
        124     32
YYYYY   123     22
        124     24

列标题为Count且没有dtype

我想我可以使用:

print orders_str[:orders_str.rfind('\n')]

2 个答案:

答案 0 :(得分:2)

您可以致电.agg(["count"])

import pandas as pd
import random
s = ["xxx", "yyy", "zzz"]
symbols = [random.choice(s) for i in range(100)]
s = [10, 20, 30]
account = [random.choice(s) for i in range(100)]
s = [11, 22, 33]
ids = [random.choice(s) for i in range(100)]
print df.groupby(["Account", "Symbols"])['OrderID'].agg(["count"])

输出:

                 count
Account Symbols       
10      xxx         11
        yyy         13
        zzz          9
20      xxx          6
        yyy         11
        zzz         14
30      xxx          6
        yyy         16
        zzz         14

答案 1 :(得分:1)

print pd.DataFrame({'Count': out_df.groupby(['Symbol', 'Account']).size()})

输出:

                Count
Symbol  Account 
XXXXX   123     34
        124     32
YYYYY   123     22
        124     24