Read duplicate values ​​in a specific column in a CSV file and return the value in another column (python2)

I'm currently trying to count duplicate values ​​in a CSV column of a file and return the value to another CSV column in python.

For example, my CSV file:

KeyID    GeneralID
145258   KL456
145259   BG486
145260   HJ789
145261   KL456

What I want to achieve is to calculate how much data the same has GeneralIDand insert it into a new CSV column. For instance,

KeyID    Total_GeneralID
145258   2
145259   1
145260   1
145261   2

I tried to split each column using the split method, but it did not work so well.

My code is:

case_id_list_data = []

with open(file_path_1, "rU") as g:
    for line in g:
        case_id_list_data.append(line.split('\t'))
        #print case_id_list_data[0][0] #the result is dissatisfying 
        #I'm stuck here.. 
+4
source share
5 answers

And if you are negative about pandas and want to stay with the standard library:

The code:

import csv
from collections import Counter
with open('file1', 'rU') as f:
    reader = csv.reader(f, delimiter='\t')
    header = next(reader)
    lines = [line for line in reader]
    counts = Counter([l[1] for l in lines])

new_lines = [l + [str(counts[l[1]])] for l in lines]
with open('file2', 'wb') as f:
    writer = csv.writer(f, delimiter='\t')
    writer.writerow(header + ['Total_GeneralID'])
    writer.writerows(new_lines)

Results:

KeyID   GeneralID   Total_GeneralID
145258  KL456   2
145259  BG486   1
145260  HJ789   1
145261  KL456   2
+1
source

:  1. CSV  2.  3.    csv   import fileinput   import sys

# 1. Read CSV file
# This is opening CSV and reading value from it.
with open("dev.csv") as filein:
    reader = csv.reader(filein, skipinitialspace = True)
    xs, ys = zip(*reader)

result=["Total_GeneralID"]

# 2. Generate new column value
# This loop is for counting the "GeneralID" element.
for i in range(1,len(ys),1):
    result.append(ys.count(ys[i]))

# 3. Add value to the file back
# This loop is for writing new column
for ind,line in enumerate(fileinput.input("dev.csv",inplace=True)):
    sys.stdout.write("{} {}, {}\n".format("",line.rstrip(),result[ind]))

- , panda - .

+3
import pandas as pd
#read your csv to a dataframe
df = pd.read_csv('file_path_1')
#generate the Total_GeneralID by counting the values in the GeneralID column and extract the occurrance for the current row.
df['Total_GeneralID'] = df.GeneralID.apply(lambda x: df.GeneralID.value_counts()[x])
df = df[['KeyID','Total_GeneralID']]
Out[442]: 
    KeyID  Total_GeneralID
0  145258                2
1  145259                1
2  145260                1
3  145261                2
+1
source

You can use pandas:

  • at first read_csv
  • get the number of values ​​in a column GeneralIDusing value_counts, renameby output column
  • join to the original DataFrame

import pandas as pd

df = pd.read_csv('file')
s = df['GeneralID'].value_counts().rename('Total_GeneralID')
df = df.join(s, on='GeneralID')
print (df)
    KeyID GeneralID  Total_GeneralID
0  145258     KL456                2
1  145259     BG486                1
2  145260     HJ789                1
3  145261     KL456                2
+1
source

Use csv.reader instead of the split () method. Its easier.

thank

0
source

Source: https://habr.com/ru/post/1675578/


All Articles