0

I have this data frame.

  City     Name
0   Seattle    Alice
1   Seattle      Bob
2  Portland  Mallory
3   Seattle  Mallory
4   Seattle      Bob
5  Portland  Mallory

I need to split the dataframe based on city. So I need a seperate Seattle and Portland dataframe.

g = df.groupby( [ "City"] )

I can group by city but I need to get individual data frames for Seattle and Portland. I don't want to apply any aggregate function to the dataframe just yet.

Dataframe for Seattle

  City     Name
    0   Seattle    Alice
    1   Seattle      Bob
    3   Seattle  Mallory
    4   Seattle      Bob

Dataframe for Portland

 City     Name
    2  Portland  Mallory
    5  Portland  Mallory
Bryce Ramgovind
  • 3,127
  • 10
  • 41
  • 72
  • `df_s = df[df['City'] == 'Seattle']` – Stael Apr 11 '17 at 09:47
  • basically you can reuse the answer from the dupe without the list comprehension – EdChum Apr 11 '17 at 09:48
  • I don't know how many cities there are – Bryce Ramgovind Apr 11 '17 at 09:48
  • 1
    @JavaBeginner: you can use dictionary comprehension: `{city:df[df['City'] == city] for city in set(df['City'])}` this will construct a dictionary containing dataframes for every city. – Willem Van Onsem Apr 11 '17 at 09:49
  • @WillemVanOnsem: while that will work, it can be very slow because of the repeated loops over the frame. The linked groupby approach will be faster (for large frames, anyhow, and for small ones it doesn't really matter.) – DSM Apr 11 '17 at 12:13

0 Answers0