Calculation between two columns in Python?

2024/11/16 15:20:31

When I tried to do some calculation between two columns (like division), I get an error: column_ratio[x]=(float(column1[y]))/(float(column2[z])) TypeError: tuple indices must be integers, not str. Could someone help me to solve this problem?

from itertools import izip_longest
import csv
with open(r"C:\Users\a.txt", 'rb') as csv1,\open(r"C:\Users\b.txt", 'rb') as csv2, \open(r"C:\Users\c.txt", 'rb') as csv3, \open(r"C:\Users\out.txt", 'w') as out:spam1 = csv.reader(csv1, delimiter=',')spam2 = csv.reader(csv2, delimiter=',')spam3= csv.reader(csv3, delimiter=',')column1=list(izip_longest(*spam1))[-1]column2=list(izip_longest(*spam2))[-1]column3=list(izip_longest(*spam3))[-1]column_ratio=[]for x,y,z in izip_longest(column_ratio, column1, column2):column_ratio[x]=(float(column1[y]))/(float(column2[z]))for i,j,m,n,x in izip_longest(spam1,column1, column2, column3, column_ratio):out.write(','.join(i)+','+j+','+m+','+n+','+x+'\n')
Answer

When you parse with the CSV reader, it has no way of knowing that the data should be an integer, a float, a string, etc. All comma-delimited data is parsed as a string, and it's up to you to convert it to the right type. You'll need to coerce the string to an integer to use it as an index.


Take the following CSV:

Index One, Index Two, Index Three
0,1,2

When parsing it:

x, y, z = reader.next()  # ['0', '1', '2']
print my_tuple[x]  # TypeError: tuple indices must be integers, not str
print my_tuple[int(x)]  # Expected result
https://en.xdnf.cn/q/120314.html

Related Q&A

Why does input() always return a string?

Here is my code:age = input("How old are you?: ") print (age) print (type(age))Result:How old are you?: 3535class str <<--- This is problem!But, If I use.. age = int(input("How …

Windowed mode cannot run

Why does pyinstaller exe not run in windowed mode but fine without it? I have changed over to a windows OS from Linux. Never had any issue before hand, how do I correct this.

inserting a variable into an fstring using .replace()

I have a code something similar to bellow. name = Dave message = f<name> is a really great guy! message = message.replace(<name>, {name}) print(message)the variables are a little more compl…

How to allow caps in this input box program for pygame?

I found this input box module on the internet but it only allows lower case no upper. So could someone tell me what to change in the module to allow caps as im creating a small multiplayer game and i n…

Why testing error rate increases at high values of K in KNN algorithm?

I am getting the error rates like this up to 20 values what might be the reason for this ?k_values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Error [0.0, 0.0, 0.0, 0.0, 0…

Divide and Conquer. Find the majority of element in array

I am working on a python algorithm to find the most frequent element in the list. def GetFrequency(a, element): return sum([1 for x in a if x == element])def GetMajorityElement(a):n = len(a)if n == …

Scraping dynamic webpage using Python

I am trying to scrape following dynamically generated webpage https://www.governmentjobs.com/careers/capecoral?page=1 Ive used requests, scrapy, scrapy-splash but I simply get page source code and I d…

numba cuda deprecation error : how to update my code?

Im running a jupyter notebook frome here : https://github.com/noahgift/nuclear_powered_command_line_tools/blob/master/notebooks/numba-cuda.ipynb The docs of current numba/cuda is here : https://numba.r…

reverse nested dicts using python

I already referred these posts here, here and here. I have a sample dict like as shown below t = {thisdict:{"brand": "Ford","model": "Mustang","year": …

python how to generate permutations of putting a singular character into a word

No idea how to word this so the title sucks my bad, Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it. So if my word was Cats, I want to get every permu…