Franklin
Franklin

Reputation: 21

Python Groupby Iteration Error

Getting the following error after running the following code:

for names, group in df_group:
    print(str(names))

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

Any ideas?

df_group's output is (for example) the following

symbol  exchange  price  
AAPL    NASDAQ    154.630     800
                  154.640     641
                  154.650     100
                  154.660     300
                  154.670     400
                  154.675     100
                  154.680     300
                  154.690    1390
                  154.695     100
                  154.700     360
                  154.705     100
                  154.710     671
                  154.720     190
                  154.725     100
                  154.730     400
...
XOM     ARCA  80.67                                                 1300
              80.68                                                 2721
              80.69                                                 1901
              80.7                                                   700
              80.71                                                  800
              80.72                                                  200
              80.73                                                  700
              80.74                                                  500
              80.75                                                  600
              80.76                                                  300
              80.77                                                  900
              80.78                                                  100
              80.79                                                 1000
              80.8                                                  1000
symbol  exch      price    sizesizesizesizesizesizesizesizesizesizesizesi...

And I've grouped using the following code:

df_group = df.groupby(['symbol','exchange','price'])["size"].sum()

Thanks!!

Upvotes: 0

Views: 158

Answers (1)

RPyStats
RPyStats

Reputation: 316

Looks like your attempting to iterate over a pandas series. If that's all you need, this may help.

for names, group in df_group.iteritems():
    print(names)
    print(group)

Additionally, if your looking for a pandas dataframe object instead of a series use double square brackets. This will return a multi-index dataframe. Using the method .reset_index will convert it to a regular dataframe.

# Multi-Index Dataframe
df_group = df.groupby(['symbol','exchange','price'])[["size"]].sum()
# Regular Dataframe
df_group = df.groupby(['symbol','exchange','price'])[["size"]].sum().reset_index()

Upvotes: 1

Related Questions