Reputation: 358
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
Reputation: 13426
Use str.split()
and len
:
df["count"] = df["ship_to_countries"].apply(lambda x: len(x.split(",")))
Upvotes: 3