tomoc4
tomoc4

Reputation: 358

count total number of comma separated countries in pandas column

I have a list of countries I would like to get a count of in a data frame column.

 ship_to_countries

 Albania, Algeria, Azerbaijan, Bahrain, France, Georgia
 Ireland, England, France, Germany
 France, Germany,
 Ireland

How can I create a column to the right which has the count of countries in pandas?

I've tried this solution but I get a count of how many times a single country is listed. so If Isreal is in my column once 16 times I get 16. I'd like only get only how many countries are in each pandas row.

(df['ship_to_countries'].str.count(',')
                      .add(1)
                      .groupby(df.ship_to_countries)
                      .sum())

Upvotes: 1

Views: 788

Answers (1)

Sociopath
Sociopath

Reputation: 13426

Use str.split() and len:

df["count"] = df["ship_to_countries"].apply(lambda x: len(x.split(",")))

Upvotes: 3

Related Questions