简体   繁体   English

如何计算csv文件中的特定数据并在python中打印该数字?

[英]How do I count specific data from a csv file and print that number in python?

For example, If i wanted to count the number of males in the 'sex' column and print that number in python. 例如,如果我想计算“性别”列中的男性人数,并在python中打印该人数。 How would I do that? 我该怎么做?

截图

import csv

pf = open("yourcsv.csv", "r")

read = csv.reader(pf)

male_count = 0
for r in read:
    if r[1] == 'Male':
        male_count += 1
pf.close()

print("Male count: {}".format(male_count))

Given my_csv.csv 鉴于my_csv.csv

id,name,sex
1,aaa,m
2,bbb,m
3,bbb,f
4,bbb,f
5,bbb,m
6,bbb,m

You can count the number of males with: 您可以使用以下方法计算男性人数:

import pandas as pd
df = pd.read_csv('my_csv.csv')
print(df['sex'].value_counts()['m']) # prints 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Python 中的 CSV 文件中抓取特定数据? - How do I scrape specific data from a CSV file in Python? 如何在python中打印csv文件中的记录总数? - How do I print the total number of records from a csv file in python? 如何使用Python从包含特定单词的文件中打印行数? - How do I print the number of lines from a File that contains a specific word using Python? 如何从python中的不同输入打印到CSV文件 - how do i print to a a CSV file from different inputs in python 如何从 python 中的 CSV 文件打印特定字段? - How do I print a particular field from a CSV file in python? 如何在csv文件中的行中打印特定字段,以及如何将输入内容写入csv文件? - How do I print specific fields from rows in a csv file and how to write input to a csv file? 如何从 python 的字段中提取特定数据进行打印? - How do I extract a specific data from a Field in python to print it? 如何读取csv文件中的数据并打印特定的文件? - how do you read data in csv file and print specific ones? 如何在 csv 文件中搜索特定字段然后在 Python 中打印整行 - How do I search for a specific field in a csv file then print the entire row in Python 如何使用 Python 计算 csv 中唯一值的数量 - How do I count the number of unique values in a csv using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM