简体   繁体   中英

Converted to Float and Int, TypeError: can't multiply sequence by non-int of type 'float' Python 2.7

I am trying to open a CSV file, iterate over its row's and convert the final part of row to a new number created by multiplying the existing value with a floating point number.

Row[8] of the CSV file returns a string that is represented either as an int , NaN or float . I've replaced the NaN , found out about slicing to limit the string to 5 characters. Then I've tried to use a conditional that will convert the appropriate string into either an int or a float .

The final part of the for loop, I am trying to multiply the appropriate part of the CSV file by a float (1.98) and this is where I get the error ( TypeError: can't multiply sequence by non-int of type 'float' ). If I change this to 2 ie an int the script runs.

I feel like the problem must exist in the conversion from string using the if else to either int or float but i'm not sure where. Any hints would be appreciated.

for row in csv_f:
        row[8] = row[8][:5]
        if isinstance(row[8], float):
            row[8] = float(row[8])
        if isinstance(row[8], int):
            row[8] = int(row[8])
        row[8] = row[8] * 1.9
        print row[8]

row[8] is a string

type(row[8])
<class 'str'>

Condition if isinstance is never executed.

Why when You change to 2 then work? Because 'a' * 2 == 'aa'

In your code, neither of

    if isinstance(row[8], float):
        row[8] = float(row[8])
    if isinstance(row[8], int):
        row[8] = int(row[8])

will be executed, as row[8] is of type string .

What you need to do is to simply change it to row[8] = float(row[8]) and it will be OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM