user899714
user899714

Reputation: 465

compare one column to another in csv file in Python

Hi i want to compare column a of a csv file with column b of the same csv file as follows:

column a:
8,67,55,32,44,70,9,10,79,21

column b:
22, 45, 6, 22, 3, 22, 6, 7,22,5

i want the user to enter a number lets say: '8' usin rawinput command. Then search number corresponding to 8 in other coulmn(b). This should give 22. once 22 is obtained i want all other numbers of column(a) that correspond to the numbr 22 in column b to be listed/displayed. pls help me over how to go about this?

Upvotes: 0

Views: 344

Answers (2)

machine yearning
machine yearning

Reputation: 10129

Some functions that might be useful to you (selected from the python official documentation):

raw_input([prompt]) If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

str.split([sep[, maxsplit ]]) Return a list of the words in the string, using sep as the delimiter string.

list.index(x) Return the index in the list of the first item whose value is x. It is an error if there is no such item.

In addition if you're doing anything else to your numerical values it may be useful to type-cast them:

int([x[, base]]) Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace.

Also you may want to use a list comprehension, such as:

>>> my_str_vals = ['20', '42', '14.2', '808.0']
>>> my_floats = [float(val) for val in my_str_vals]
>>> my_str_vals[2]
'14.2'
>>> my_floats[2]
14.2

Upvotes: 1

Ojen
Ojen

Reputation: 847

I would create a dictionary (lets call it dictA) for the incoming data where the keys are the column a numbers and the values column b.

I would also create a second dictionary (dictB) where the keys are the column b numbers and the values are lists of the corresponding values from column a.

So for the example you give, the user would input 8, which would be looked up in dictA, and 22 would be found. Then 22 would be looked up in dictB and the value of 22 in dictB is [8,32,79]. Return that list however you see fit.

This all assumes that the values in column a are unique.

Upvotes: 1

Related Questions