PythonLearner
PythonLearner

Reputation: 93

collections.Counter for csv file and updating blank cells

I am importing data from a csv file; and trying to determine a user type. In specific, I am using the python module collections.

My data set has blank fields thus when I execute the following script type_of_users=user_data.most_common() I get the following result:

The type of users are :

[('Subscriber', 269149), ('Customer', 30159), ('', 692)]

Is there a way to update the ('',692) with ('Unknown User Type',692)?

Upvotes: 0

Views: 44

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40888

You could use a list comprehension on the results of .most_common() after reading the file:

>>> type_of_users = [('Subscriber', 269149), ('Customer', 30159), ('', 692)]

>>> type_of_users = [(i, j) if i else ('Unknown User Type', j)
...                  for i, j in type_of_users]

>>> type_of_users
[('Subscriber', 269149), ('Customer', 30159), ('Unknown User Type', 692)]

This takes advantage of the property that empty sequences ('') are considered False while non-empty strings are considered True.

Note that there are a number of other objects that will also evaluate in this way, so if you need to be more explicit, you should use if i != ''.

Upvotes: 1

Related Questions