PretendNotToSuck
PretendNotToSuck

Reputation: 404

How to count total uppercase letters in all list elements without converting to string

My data:

import pandas as pd
data = {'game': [1, 2], 'moves': [['D4', 'd5', 'NF4'],['d5', 'c6', 'Be4']]}
df = pd.DataFrame(data) 
| game |     moves    |
|------|--------------|
| 1    |[D4, d5, NF4]  |
| 2    |[d5, c6, Be4] |

For each row, I want to extract the number of uppercase letters in the first n elements of the list in the column 'moves'. So far I have this solution:

count = []
for row in df.moves:
    count.append(sum(1 for elem in listToString(row[0:10]) if elem.isupper()))

This works, but I would prefer a solution which does not involve concatenating the string elements of the lists. Is there such a thing?

Output:

[3, 1]

Upvotes: 2

Views: 88

Answers (2)

Jan Pedersen
Jan Pedersen

Reputation: 64

Using list comprehensions it is possible to do:

count  = [[y[0].isupper() for y in x].count(True) for x in data['moves']]

or if all uppercase letters needs counted:

count  = [sum([sum(1 for elem in y if elem.isupper()) for y in x]) for x in data['moves']]

and a bit better:

count  = [sum(1 for elem in ''.join(x) if elem.isupper())  for x in data['moves']]

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

Try this:

count = df['moves'].apply(lambda x: sum(1 for i in x[:10] for y in i if y.isupper())).tolist()

Output:

[3, 1]

Upvotes: 2

Related Questions