![](/img/trans.png)
[英]How to convert pandas data frame into list of tuples<string, list of list>
[英]How to convert data type for list of tuples string to float
g = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
這里'10.000'
和'10'
是字符串
如何轉換為以下格式,字符串為浮點數
預計出局
[('Books', 10.000),('Pen', 10),('test', 'a')]
這里10.000
和10
是浮點數, a
必須是字符串
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)
我收到錯誤AttributeError: 'tuple' object has no attribute 'isalpha'
包含'a'
值(即不可轉換為浮點數的值),您可以依靠這個答案:
def tofloat(price):
try: return float(price)
except ValueError: return price #we do this when price is not convertable to float
之后,繼續進行列表理解:
result = [(item, tofloat(price)) for item, price in g]
result
將是:
[('Books', 10.0), ('Pen', 10.0), ('test', 'a')]
float
10 和 10.000 之間沒有區別,因此如果您希望 10 和 10.000 以不同的方式出現,您應該將它們保留為字符串。
對評論的反思
要檢查數值是float
而不是int
,我們可以這樣做:
print([type(number) for item, number in result])
給出 output:
[<class 'float'>, <class 'float'>, <class 'str'>]
按要求。
筆記本在這里可用。
您的代碼有問題,因為您使用的 x 是一個元組。 您提供的列表的元素是元組類型 (String,String),因此您需要對元組的元素再進行一次迭代。 我已將您的代碼修改為:
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)
我已經測試了代碼:
//input
result= [('Books', '10.000'),('Pen', '10'),('test', 'a')]
//output
[('Books', 10.0), ('Pen', 10), ('test', 'a')]
您需要使用每個元組中的正確值:
for first_value, second_value in result:
if isinstance(second_value, int):
...
else isinstance(second_value, float):
...
但目前尚不清楚您要完成什么。
data = [('Books', '10.000'),('Pen', 10)]
print([(a,float(b)) for a,b in data])
這可以幫助遍歷循環並將元組中的第二項轉換為浮動
轉換的 10,000 的數量到底是多少? 有 2 個選項。 10.0 或 10000.0
它不適用於涉及這封信的情況。
參考數據data = [('Books', '10.000'),('Pen', 10)]
步長:10000.0
print([(key,float(str(value).replace('.',''))) for key, value in data])
# [('Books', 10000.0), ('Pen', 10.0)]
step: 10.0 這已經在上面給出了。 但讓我記下以避免混淆。
print([(key, float(str(value))) for key, value in data])
# [('Books', 10.0), ('Pen', 10.0)]
您當前的方法嘗試在元組而不是字符串上使用 the.isalpha() function。 該錯誤告訴您元組 object 沒有內置 isalpha() function。
使用您的方法,您需要解耦元組,以便您可以檢查每個元組內的字符串,然后運行您的邏輯。 在代碼中,我在 function 中抽象出您的檢查邏輯,以嘗試更清楚地表明您需要為列表中的每個元組運行兩次。
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')]
我會嘗試以下方法:
g = [('Books', float('10.000')),('Pen', float('10')),('test', 'a')]
嘗試這個
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')]
# 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]
有很多方法可以制定可行的解決方案,但我認為最好的方法是糾正您的解決方案
在你的代碼中
for x in result:
x 的值是: ('Books', '10.000'),('Pen', '10'),('test', 'a') 所以我們需要修改條件以查看每個元素的第二個元素元組
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.