# Count number of words per row

Given a pandas dataframe, we have to count number of words per row.
Submitted by Pranit Sharma, on December 09, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.

## Problem statement

Suppose we are given the data frame with some columns of string type and we need to create a new column in this dataframe that contains the word count for the respective row. We need to total the number of words and not the frequencies of each word.

## Counting number of words per row

For this purpose, we will use a very simple approach to count the words. We know that it a sentence has a +1 number of white spaces then words. Hence, we will count all the white spaces using the count method and add 1 to it.

Let us understand with the help of an example,

## Python program to count number of words per row

```# Importing pandas
import pandas as pd

# Creating a dictionary
d = {'A':['Ram is a good boy','India is my country','This is a tutorial of includehelp']}

# Creating a dataframe
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Counting words
res = df['A'].str.count(' ') + 1

# Display result
print("Result:\n",res,"\n")
```

### Output

The output of the above program is: