How to convert data type for list of tuples string to float
Asked Answered
L

10

9

g = [('Books', '10.000'),('Pen', '10'),('test', 'a')]

Here '10.000' and '10' are strings

How to convert to below format, string to float

Expected out

[('Books', 10.000),('Pen', 10),('test', 'a')]

Here 10.000 and 10 are floats and a has to be string

newresult = []
for x in result:
    if x.isalpha():
        newresult.append(x)
    elif x.isdigit():
        newresult.append(int(x))
    else:
        newresult.append(float(x))
print(newresult)

I got error AttributeError: 'tuple' object has no attribute 'isalpha'

Live answered 3/7, 2020 at 14:56 Comment(1)
What do you want to do? Please specify properly. Convert which to what?Stockjobber
M
4

you have a problem in your code because the x that you are using is a tuple. The elements of the list you provided are tuples type (String,String) so you need one more iteration on the elemts of the tuples. I have modified your code to :

newresult = []
for tuple in result:
    temp = []
    for x in tuple:
        if x.isalpha():
            temp.append(x)
        elif x.isdigit():
            temp.append(int(x))
        else:
            temp.append(float(x))
    newresult.append((temp[0],temp[1]))
print(newresult)

I have tested the code :

 //input 
 result= [('Books', '10.000'),('Pen', '10'),('test', 'a')]
 //output
 [('Books', 10.0), ('Pen', 10), ('test', 'a')]
Marsala answered 9/7, 2020 at 17:52 Comment(0)
B
5

With the 'a' value (ie a value not convertible to float) included, you can do, relying on this answer:

def tofloat(price):
    try: return float(price)
    except ValueError: return price #we do this when price is not convertable to float

After, proceed with a list comprehension:

result = [(item, tofloat(price)) for item, price in g]

result will be:

[('Books', 10.0), ('Pen', 10.0), ('test', 'a')]

There is no difference between float 10 and 10.000, so if you want 10 and 10.000 to appear in distinct ways you should keep them strings.



Reflection on comments

To check that the numerical values are float and not int, we can do:

print([type(number) for item, number in result])

giving an output:

[<class 'float'>, <class 'float'>, <class 'str'>]

as required.

enter image description here

Notebook avaliable here.

Blotchy answered 8/7, 2020 at 6:51 Comment(4)
The 10.000 will convert to float, the 10 will not, but will convert to int. Floats will print as 10.0, while ints will just print 10.Widgeon
I don't think you are right about that, updated my answer. Lmk if you still think it's wrong.Blotchy
Well, you have to use some code to decide whether to use int(x) or float(x) - you're right that if you dump both of them into float(x) you'll end up with a float (10.0 instead of 10). Just pointing out the question was asking for 10.0 on the first tuple and just 10 for the second tuple, so your code should figure out a way to differentiate and delivery that output.Widgeon
Oh, I see you point now. I relied on the title of the OP, which specifically asks for float. You are right, the body of the question says otherwise.Blotchy
M
4

you have a problem in your code because the x that you are using is a tuple. The elements of the list you provided are tuples type (String,String) so you need one more iteration on the elemts of the tuples. I have modified your code to :

newresult = []
for tuple in result:
    temp = []
    for x in tuple:
        if x.isalpha():
            temp.append(x)
        elif x.isdigit():
            temp.append(int(x))
        else:
            temp.append(float(x))
    newresult.append((temp[0],temp[1]))
print(newresult)

I have tested the code :

 //input 
 result= [('Books', '10.000'),('Pen', '10'),('test', 'a')]
 //output
 [('Books', 10.0), ('Pen', 10), ('test', 'a')]
Marsala answered 9/7, 2020 at 17:52 Comment(0)
K
3

You need to use the right value from each tuple:

for first_value, second_value in result:    
    if isinstance(second_value, int):
        ...
    else isinstance(second_value, float):
        ...
 
  1. first_value will be "Books"
  2. second_value will be '10.000'

But it's not clear what you are trying to accomplish.

Keldon answered 3/7, 2020 at 15:0 Comment(3)
Though I didn't know the isalpha() method it appears that it is a string method and will throw an exception if the type of the variable is something differentBeing
@Being you can use isinstance(x, int) and isinstance(x, float)Keldon
@Keldon - I know, but it is not specified in your code :DBeing
R
1
data = [('Books', '10.000'),('Pen', 10)]
print([(a,float(b)) for a,b in data]) 

this can help iterate through a loop and convert you second item in tuple to float

Rhaetian answered 3/7, 2020 at 15:1 Comment(1)
@Nons not to worry this code will work for your modification too, but one small thing neeed to take care is for 10.000 the output as float is 10.0 and 10 will not be 10 because python does not work in that wayRhaetian
K
1

What exactly is the number of 10,000 converted? There are 2 options. 10.0 or 10000.0

It will not work in cases involving this letter.

referance data data = [('Books', '10.000'),('Pen', 10)]

step: 10000.0

print([(key,float(str(value).replace('.',''))) for key, value in data])
# [('Books', 10000.0), ('Pen', 10.0)]

step: 10.0 this is already given above. But let me take a note to avoid confusion.

print([(key, float(str(value))) for key, value in data])
# [('Books', 10.0), ('Pen', 10.0)]
Kendyl answered 8/7, 2020 at 6:51 Comment(0)
O
1

Your current approach tries to use the .isalpha() function on a tuple rather than a string. The error is telling you that the tuple object does not have the isalpha() function built in.

Using your approach, you'd need to decouple the tuple so that you could check the string inside each tuple, then run your logic. In the code, I abstracted your checking logic out in a function to try to show more clearly that you'd need to run it twice for each tuple in the list.

def convert_to_proper_type(value):
    if value.isalpha():
        value = str(value)
    elif value.isdigit():
        value = int(value)
    else:
        value = float(value)
    return value

result = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
newresult = []

for (value_one, value_two) in result:
    # If all chars in both are alphabets
    value_one = convert_to_proper_type(value_one)
    value_two = convert_to_proper_type(value_two)
    newresult.append((value_one, value_two))

print(newresult)
# [('Books', 10.0), ('Pen', 10), ('test', 'a')]
Orlene answered 10/7, 2020 at 21:43 Comment(0)
E
0

I would try with the following:

g = [('Books', float('10.000')),('Pen', float('10')),('test', 'a')]
Eponymous answered 13/7, 2020 at 3:7 Comment(0)
D
0

Try this

list_ = [('Books', '10.000'),('Pen', '10'),('test', 'a')]

def fix_list(list_):
    def check_and_convert(val_1, val_2):
        try:
            return val_1, float(val_2)
        except:
            return val_1, val_2

    ret_list = []
    for val_1, val_2 in list_:
        ret_list.append(check_and_convert(val_1, val_2))
    return ret_list


print(fix_list(list_))
# >>> [('Books', 10.0), ('Pen', 10.0), ('test', 'a')]
Diazonium answered 14/7, 2020 at 14:17 Comment(0)
E
0
# Helper Function check if string is a number
def is_number(n:str):
    try:
        float(n)
    except ValueError:
        return False
    return True

# Filter the list of numbers using the following 
>>> g = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
>>> [float(char) if is_number(char) else char for char in map(lambda x:x[1],g)]
>>> [10.0, 10.0, 'a']
>>> # If only numbers are needed
>>> [float(char) if is_number(char) for char in map(lambda x:x[1],g)]
>>> [10.0, 10.0]
Engen answered 15/7, 2020 at 0:11 Comment(0)
S
0

there is many ways to make a working solution, but I think that the best is to correct your solution

in your code

for x in result:

the values of x are : ('Books', '10.000'),('Pen', '10'),('test', 'a') so we need to modify the condition to look at the second element of each tuple

newresult = []
for x in result:
    if x[1].isalpha():
        newresult.append(x)
    elif x[1].isdigit():
        newresult.append((x[0],int(x[1])))
    else:
        newresult.append((x[0],float(x[1])))
print(newresult)
Steelworker answered 15/7, 2020 at 2:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.