1

colors.csv

id  name    rgb         is_trans
0   -1  Unknown 0033B2  f
1   0   Black   05131D  f
2   1   Blue    0055BF  t

How do you count how many f & t, (something like below)

colors_summary = colors.count('is_trans')
print(colors_summary)

Looking for Result

is_trans    id  name    rgb
f   107 107 107
t   28  28  28
6
  • Uh, what kind of object is colors? Is this a pandas dataframe? How is this question related to csv? Commented Mar 3, 2019 at 19:15
  • You can make use of Counter class from collections built-in module, but only if that's not a pandas DataFrame. Commented Mar 3, 2019 at 19:16
  • import pandas as pd colors = pd.read_csv('datasets/colors.csv') Commented Mar 3, 2019 at 19:18
  • edit that into the question please. And you'll probably want to add a pandas tag while you're at it. Commented Mar 3, 2019 at 19:20
  • how does your output match the input? can you explain plz? do you mean df.groupby('is_trans').count().reset_index() ? Commented Mar 3, 2019 at 19:26

2 Answers 2

1

let say you have

color_df # dataframe object

you can do that:

result_df = color_df.groupby('is_trans').count()
print(result_df) # should give you what you ask for.
Sign up to request clarification or add additional context in comments.

1 Comment

yess! groupby worked, I did not know, python has this like SQL
0

and an alternative with stdlib csv & Counter.

color_csv = """id  name    rgb         is_trans
0   -1  Unknown 0033B2  f
1   0   Black   05131D  f
2   1   Blue    0055BF  t"""

import csv
from collections import Counter
from io import StringIO

settings = dict(delimiter=' ', skipinitialspace=True)
creader = csv.reader(StringIO(color_csv), **settings)
headers = next(creader)
counter = Counter((row[-1] for row in creader))
print(counter)

Counter({'f': 2, 't': 1})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.