Rectangle 27 126

os.listdir() will be slightly more efficient than using glob.glob. To test if a filename is an ordinary file (and not a directory or other entity), use os.path.isfile():

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
folder_path
os.path.filename(name)

For recursively counting files nested inside directories, you might be better off with the os.walk() solution.

What is the benefit of using os.path.join(DIR, name) over DIR + '/' + name? The latter is shorter and, IMO, more clear than the former. Is there perhaps some OS:es on which the latter would fail?

@HelloGoodbye That's exactly the reason.

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 123

os.listdir() will be slightly more efficient than using glob.glob. To test if a filename is an ordinary file (and not a directory or other entity), use os.path.isfile():

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
folder_path
os.path.filename(name)

For recursively counting files nested inside directories, you might be better off with the os.walk() solution.

What is the benefit of using os.path.join(DIR, name) over DIR + '/' + name? The latter is shorter and, IMO, more clear than the former. Is there perhaps some OS:es on which the latter would fail?

@HelloGoodbye That's exactly the reason.

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 45

import os

path, dirs, files = os.walk("/usr/lib").next()
file_count = len(files)
path, dirs, files = os.walk("/usr/lib").__next__()

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 43

import os

path, dirs, files = os.walk("/usr/lib").next()
file_count = len(files)
path, dirs, files = os.walk("/usr/lib").__next__()

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 5

The basic idea is to count the number of created instances in some static variable. I would implement it like this. Simpler approaches exist, but this one has some advantages.

template<class T, int maxInstances>
class Counter {
protected:
    Counter() {
        if( ++noInstances() > maxInstances ) {
            throw logic_error( "Cannot create another instance" );
        }
    }

    int& noInstances() {
        static int noInstances = 0;
        return noInstances;
    }

    /* this can be uncommented to restrict the number of instances at given moment rather than creations
    ~Counter() {
        --noInstances();
    }
    */
};

class YourClass : Counter<YourClass, 4> {
}

As long as you're defining a template superclass, you might as well add a second template parameter for the max number of instances. I.e.: template<class T, int MAX_INSTANCES> class Counter {...};

+1. But better to wrap the static member into an inline accessor function, to avoid the template definition in the source file.

@EdwardLoper, it was kind of a compliment to Luchian Grigore's answer, where he preserves that constant from the question, found it funny, will edit, thanks

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c++ - Restrict the number of object instantiations from a class to a g...

c++ object instantiation
Rectangle 27 8

Say I have the following DataFrame

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])

You could count a single column by

df.A.count()
#or
df['A'].count()

The cool thing (or one of many w.r.t. pandas) is that if you have NA values, count takes that into consideration.

df['A'][1::2] = np.NAN
df.count()

The result would be

A    3
 B    5

pandas python how to count the number of records or rows in a datafram...

count dataframe pandas
Rectangle 27 35

To count the number of appearances:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1
a = set(a)

+1 for collections.defaultdict. Also, in python 3.x, look up collections.Counter. It is the same as collections.defaultdict(int).

@hughdbrown, actually Counter can use multiple numeric types including float or Decimal, not just int.

python - How to count the frequency of the elements in a list? - Stack...

python counter frequency counting
Rectangle 27 7

Simply, row_num = df.shape[0] # gives number of rows, here's the example:

import pandas as pd
import numpy as np

In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])

In [323]: df
Out[323]: 
      col_1     col_2
0 -0.894268  1.309041
1 -0.120667 -0.241292
2  0.076168 -1.071099
3  1.387217  0.622877
4 -0.488452  0.317882

In [324]: df.shape
Out[324]: (5, 2)

In [325]: df.shape[0]   ## Gives no. of rows/records
Out[325]: 5

In [326]: df.shape[1]   ## Gives no. of columns
Out[326]: 2

pandas python how to count the number of records or rows in a datafram...

count dataframe pandas
Rectangle 27 21

For all kind of files, subdirectories included:

import os

list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files
import os

onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 17

For all kind of files, subdirectories included:

import os

list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files
import os

onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)

wont that include subdirectories in the count, and so not be the number of files?

Thanks @beresfordt , I've made the editing. Sorry for the delay. I hope it works.

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 16

import fnmatch

print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))

This is much faster (about half the time with my testing on a directory with 10,000 files) if you know the pattern you're looking for, rather then testing each file with os.path.isfile() as the accepted answer does. Also significantly faster than glob.glob().

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 15

import fnmatch

print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))

This is much faster (about half the time with my testing on a directory with 10,000 files) if you know the pattern you're looking for, rather then testing each file with os.path.isfile() as the accepted answer does. Also significantly faster than glob.glob().

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 10

def directory(path,extension):
  list_dir = []
  list_dir = os.listdir(path)
  count = 0
  for file in list_dir:
    if file.endswith(extension): # eg: '.txt'
      count += 1
  return count

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 52

CREATE FUNCTION dbo.CountOccurancesOfString
(
    @searchString nvarchar(max),
    @searchTerm nvarchar(max)
)
RETURNS INT
AS
BEGIN
    return (LEN(@searchString)-LEN(REPLACE(@searchString,@searchTerm,'')))/LEN(@searchTerm)
END
SELECT * FROM MyTable
where dbo.CountOccurancesOfString(MyColumn, 'MyString') = 1

A slight improvement would be to use DATALENGTH()/2 instead of LEN(). LEN will ignore any trailing whitespace so dbo.CountOccurancesOfString( 'blah ,', ',') will return 2 instead of 1 and dbo.CountOccurancesOfString( 'hello world', ' ') will fail with divide by zero.

Rory's comment is helpful. I found that I could just replace LEN with DATALENGTH in Andrew's function and get the desired result. It seems that dividing by 2 is not necessary with the way the math works out.

@AndrewBarrett : What append when several strings have the same length?

DATALENGTH()/2 is also tricky because of non-obvious char sizes. Look at stackoverflow.com/a/11080074/1094048 for simple and accurate way.

sql server - How do you count the number of occurrences of a certain s...

sql-server tsql
Rectangle 27 9

def directory(path,extension):
  list_dir = []
  list_dir = os.listdir(path)
  count = 0
  for file in list_dir:
    if file.endswith(extension): # eg: '.txt'
      count += 1
  return count

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 8

import os
print len(os.listdir(os.getcwd()))

This might be useful sometimes but it includes subdirectories in the count also

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 8

import os
print len(os.listdir(os.getcwd()))

This might be useful sometimes but it includes subdirectories in the count also

How to count the number of files in a directory using Python - Stack O...

python count glob
Rectangle 27 5

Using hint from ron's function above I've created this formula and it worked fine :

=LEN(A1) - LEN(SUBSTITUTE(A1, "-", ""))

How to Count the Number of a Specific Character in a Cell with Excel V...

vba
Rectangle 27 2

To get the number of rows in a dataframe use:

df.shape[0]

(and df.shape[1] to get the number of columns).

As an alternative you can use

len(df)
len(df.columns)

shape is more versatile and more convenient than len(), especially for interactive work (just needs to be added at the end), but len is a bit faster (see also this answer).

count()
import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(24).reshape(8, 3),columns=['A', 'B', 'C'])
df['A'][5]=np.nan
df
# Out:
#     A   B   C
# 0   0   1   2
# 1   3   4   5
# 2   6   7   8
# 3   9  10  11
# 4  12  13  14
# 5 NaN  16  17
# 6  18  19  20
# 7  21  22  23

%timeit df.shape[0]
# 100000 loops, best of 3: 4.22 s per loop

%timeit len(df)
# 100000 loops, best of 3: 2.26 s per loop

%timeit len(df.index)
# 1000000 loops, best of 3: 1.46 s per loop
df.__len__
len(df.index)
import inspect 
print(inspect.getsource(pd.DataFrame.__len__))
# Out:
#     def __len__(self):
#         """Returns length of info axis, but here we use the index """
#         return len(self.index)

Why you should not use count()

df.count()
# Out:
# A    7
# B    8
# C    8

pandas python how to count the number of records or rows in a datafram...

count dataframe pandas
Rectangle 27 2

The Nan example above misses one piece, which makes it less generic. To do this more "generically" use df['column_name'].value_counts() This will give you the counts of each value in that column.

d=['A','A','A','B','C','C'," " ," "," "," "," ","-1"] # for simplicity

df=pd.DataFrame(d)
df.columns=["col1"]
df["col1"].value_counts() 
      5
A     3
C     2
-1    1
B     1
dtype: int64
"""len(df) give you 12, so we know the rest must be Nan's of some form, while also having a peek into other invalid entries, especially when you might want to ignore them like -1, 0 , "", also"""

and if NaNs are wanted use: df["col1"].value_counts(dropna=False)

pandas python how to count the number of records or rows in a datafram...

count dataframe pandas