Splitting filename and summing index

Viewed 77

I have a directory of files with a format like test_001_3.wav. The first number is just an ID whereas the second number is an index. I want to loop through these filenames and sum the index for each ID. For example, taking the following data

test_001_0.wav
test_001_1.wav
test_001_2.wav
test_002_0.wav
test_002_1.wav

Returned would be

total for test_001: 3
total for test_002: 2

My current code is below. It correctly sums the indexes however I don't know how to make it work for the entire array of filenames.

samples = []
for filename in filenames:
    file_id = filename.split('_')[1].split('.')[0]
    index = filename.split('_')[-1].split('.')[0]
    samples.append([file_id, index])
        
count=0
for sample in samples:
    if sample[0] == '001':
        count+=1

print(samples)  # [['001', '0'], ['001', '1'], ['001', '2'], ['002', '0'], ['002', '1']]   
print(count)    # 3
1 Answers

If you want to use pandas and assuming this is in a dataframe you could use something along this line:

df = pd.read_excel('C:\\Users\\\Desktop\\test_xcel.xlsx', index_col=None, header=None)

df[0] = df[0].map(lambda x: str(x)[:-6])
df = df.groupby([0]).size().reset_index(name='count')
print(df)

          0  count
0  test_001      3
1  test_002      2

This is all assuming that the dataframe is formatted in an excel file and contains no column names.

Edit: To account for your current update to the question maybe try this out:


for k, g in itertools.groupby(files, key=lambda x:re.search('_(\d+)_', x).group(1)):
    print k, len(list(g))

Related