2

I am starting with data of city transits with an additional column containing the mode of transportation

Orig   Dest    Type
NY     SF      Train
NY     SF      Plane
NO     NY      Plane
SE     NO      Plane
SE     NO      Train

I want to aggregate it such that each unique value in Type becomes a column with counts of that Type for each unique Orig/Dest pair

Orig  Dest  Plane  Train
NY    SF    1      1
NO    NY    1      0
SE    NO    1      1

I know some basic aggregation using pd.groupby but can only aggregate so far as to get just basic counts of the Orig/Dest pairs using:

df.groubpy(['Orig','Dest'])['Type'].count()

1 Answer 1

2

You can use nunique and unstack. Last reset_index and rename_axis (new in pandas 0.18.0):

print (df.groupby(['Orig','Dest', 'Type'])['Type']
         .nunique()
         .unstack()
         .fillna(0)
         .astype(int)
         .reset_index()
         .rename_axis(None, axis=1))

  Orig Dest  Plane  Train
0   NO   NY      1      0
1   NY   SF      1      1
2   SE   NO      1      1
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was exactly what I was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.