Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Pandas Series.str.count() Method



TheSeries.str.count() method in Pandas allows you to efficiently count the occurrences of a specified regex pattern within each string element of a Series or Index.

This method returns a Series or Index containing the number, representing how many times a specified regular expression is found in each string. This method is useful for analyzing and summarizing text data.

Syntax

Following is the syntax of the PandasSeries.str.count() method −

Series.str.count(pat, flags=0, **kwargs)

Parameters

TheSeries.str.count() method accepts the following parameters −

  • pat − A string representing the valid regular expression pattern to count.

  • flags − An integer value for regex flags from the re module. Default is 0 (no flags).

  • **kwargs − Additional arguments for compatibility with other string methods. Not used.

Return Value

TheSeries.str.count() method returns a Series or Index of the same type as the calling object, containing the integer counts of the pattern occurrences.

Example

In this example, we demonstrate the basic usage of theSeries.str.count() method by counting the occurrences of the pattern 'a' in each string of a Series.

import pandas as pdimport numpy as np# Create a Series of stringss = pd.Series(['Tutorialspoint', 'python', 'pandas', 'program', np.nan, 'example'])# Count occurrences of 'a' in each stringresult = s.str.count('a')print("Input Series:")print(s)print("\nSeries after calling str.count('a'):")print(result)

When we run the above code, it produces the following output −

Input Series:0    Tutorialspoint1            python2            pandas3           program4               NaN5           exampledtype: objectSeries after calling str.count('a'):0    1.01    0.02    2.03    1.04    NaN5    1.0dtype: float64

Example

This example demonstrates how to use theSeries.str.count() method to count the occurrences of the pattern 'he|wo' in each string of a DataFrame column.

import pandas as pd# Create a DataFrame with a column of stringsdf = pd.DataFrame(['Python', 'pandas', 'tutorialspoint'], columns=['words'])# Count occurrences of 't' or 'o' in each stringresult = df.words.str.count("t|o")print("Input DataFrame:")print(df)print("\nDataFrame column after calling str.count('t|o'):")print(result)

Following is the output of the above code −

Input DataFrame:            words0          Python1          pandas2  tutorialspointDataFrame column after calling str.count('t|o'):0    21    02    5Name: words, dtype: int64

Example

In this example, we use theSeries.str.count() method to count the occurrences of the dollar sign ('$') in each string of a Series. Note that we need to escape the dollar sign using '\\$' to search for the literal character.

import pandas as pd# Create a Series of stringss = pd.Series(['$Python', 'pandas', 'p$yt$h$on', '$$C', 'C$++$', 'Python'])# Count occurrences of '$' in each stringresult = s.str.count('\\$')print("Input Series:")print(s)print("\nSeries after calling str.count('\\$'):")print(result)

Output of the above code is as follows −

Input Series:0      $Python1       pandas2    p$yt$h$on3          $$C4        C$++$5       Pythondtype: objectSeries after calling str.count('\$'):0    11    02    33    24    25    0dtype: int64

Example

In this example, we apply theSeries.str.count() method to an Index of a Series object to count the occurrences of the pattern 'a' in each string.

import pandas as pdimport numpy as np# Create a Series of stringss1 = pd.Series([1, 2, 3, 4],    index=['Pandas', 'Python', 'Tutorialspoint', 'count'])   # Count occurrences of 'a' in each stringresult = s1.index.str.count('a')print("Input Series:")print(s1)print("\nResult after calling str.count('a'):")print(result)

Output of the above code is as follows −

Input Series:Pandas            1Python            2Tutorialspoint    3count             4dtype: int64Result after calling str.count('a'):Index([2, 0, 1, 0], dtype='int64')
python_pandas_working_with_text_data.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp