Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting colums in csv file with python [closed]

https://i.sstatic.net/Le696.png

I want to count email accounts of male and female separately the code I wrote is not working properly so can anyone help me with this, please here is my code thank you in advance

    import csv

mailAcc = {}
femailAcc = {}

with open('1000 Records.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for i in csv_reader:
        email = i[6]
        gender = i[5]
        doman = email.split('@')[-1]
        if doman in mailAcc:
            if gender == 'm':
                 mailAcc[doman] = mailAcc[doman] + 1
        else:
            mailAcc[doman] = 1

        if doman in femailAcc:
            if gender == 'F':
                femailAcc[doman] = femailAcc[doman] + 1
        else:
            femailAcc[doman] = 1
            
    print('Mail Email accounts: ', mailAcc)
    print('Femail Email Accounts: ', femailAcc)
like image 652
imhamza3333 Avatar asked Apr 06 '26 23:04

imhamza3333


1 Answers

use pandas

import pandas as pd

df = pd.read_csv('your_csv_file.csv') # read in csv
df['domain'] = df['email'].apply(lambda x: x[x.index('@')+1:]) # column with just domain

male = {} # setup male dictionary
female = {} # setup female dictionary

# iterate on unique domains to get a count of male/female and populate in dictionaries
for domain in df['domain'].unique():   
    male[domain] = df[(df['gender']=='M') & (df['domain']==domain)].shape[0]
    female[domain] = df[(df['gender']=='F') & (df['domain']==domain)].shape[0]
like image 191
bvmcode Avatar answered Apr 10 '26 13:04

bvmcode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!