Search code examples
pythonpandasgroup-by

Pandas Groupby Count Partial Strings


I am wanting to try to get a count of how many rows within a column contain a partial string based on an imported DataFrame. In the sample data below, I want to groupby Trans_type and then get a count of how many rows contain a value.

Table of Sample Data

So I would expect to see:

Grouped_Counts

First, is this possible generically without passing a link to get each types expected brand? If not, how could I pass say Car a list of .str.contains['Audi','BMW'].


Solution

  • Try this one:

    df.groupby(df["Trans_type"], df["Brand"].str.extract("([a-zA-Z])+", expand=False)).count()