Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hi, just an easy question here f 2

Status
Not open for further replies.

kingz2000

Programmer
May 28, 2002
304
0
0
DE
Hi,

just an easy question here from a beginner:)

How do I find out the value_count of X which has a condition?

For example

df['Drinks'].contains("diet").value_counts()

Thanks in advance
 
you can try something like this:
Code:
>>> def count_of_elements_containing_pattern(list_of_strings, pattern):
	return [pattern in string for string in list_of_strings].count(True)

>>> my_list = ["foo", "bar", "baz", "spam", "eggs", "foobar"]
>>> count_of_elements_containing_pattern(my_list, "foobar")
1
>>> count_of_elements_containing_pattern(my_list, "foo")
2
>>> count_of_elements_containing_pattern(my_list, "bar")
2
>>> count_of_elements_containing_pattern(my_list, "a")
4
>>> count_of_elements_containing_pattern(my_list, "z")
1
>>> count_of_elements_containing_pattern(my_list, "oo")
2
 
You are forcing us to guess that df might be a pandas dataframe.

value_counts() returns a series with the count of each unique value in a column.

Then find the thing you are interested in within that series and look up the count.
 
Out of curiosity i installed pandas and tried the previous example with it:
Code:
>>> import pandas as pd
>>> my_list = ["foo", "bar", "baz", "spam", "eggs", "foobar"]
>>> my_series=pd.Series(my_list)
>>> my_series[my_series.str.match("foobar")].count()
1
>>> my_series[my_series.str.match("foo")].count()
2
>>> my_series[my_series.str.match(".*bar")].count()
2
>>> my_series[my_series.str.match(".*a.*")].count()
4
>>> my_series[my_series.str.match(".*z.*")].count()
1
>>> my_series[my_series.str.match(".*oo.*")].count()
2
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top