簡體   English   中英

將字典的 python 值從列表轉換為浮點數

[英]Converting python value of dictionary from list to float

我通常用另一種語言編程,但目前需要 python 。 我想將此 python 字典中的字符串轉換為浮點數,但我在網上閱讀的提示並沒有像我希望的那樣工作。

example= dict({'Baker': '16,765',
 'Benton': '93,590',
 'Clackamas': '419,425',
 'Clatsop': '39,200',
 'Columbia': '51,900',
 'Coos': '63,275'})

以下結果只取第一個 integer

for key in example.keys():
    example[key] = [float(example[key][0]),float(example[key][1])]
example

Out[]: 
{'Baker': [1.0, 6.0],
 'Benton': [9.0, 3.0],
 'Clackamas': [4.0, 1.0],
 'Clatsop': [3.0, 9.0],
 'Columbia': [5.0, 1.0],
 'Coos': [6.0, 3.0]}

以下仍然是一個字符串

{k:(map(float, example[k])) for k in example}
example

Out[]: 
{'Baker': '16,765',
 'Benton': '93,590',
 'Clackamas': '419,425',
 'Clatsop': '39,200',
 'Columbia': '51,900',
 'Coos': '63,275'}

我希望你能幫忙。 我正在使用python3。 謝謝。

你犯了幾個錯誤。 使用花括號、鍵和值已經定義了一個dict 您無需再次調用dict() 然后你要么使用dict理解,要么使用map function,但你不需要兩者。 最后,您必須用點替換逗號才能進行轉換。

example = {
    'Baker': '16,765',
    'Benton': '93,590',
    'Clackamas': '419,425',
    'Clatsop': '39,200',
    'Columbia': '51,900',
    'Coos': '63,275'
}

in_float = {k: float(i.replace(',', '.')) for k, i in example.items()}
print(in_float)

如果你只想要int值而不是字符串,你只需要這個:

example = {'Baker': '16,765',
 'Benton': '93,590',
 'Clackamas': '419,425',
 'Clatsop': '39,200',
 'Columbia': '51,900',
 'Coos': '63,275'}

for key in example:
    s = example[key]
    example[key] = [int(item) for item in s.split(',')]

print(example)

Output:

{'Baker': [16, 765], 
'Benton': [93, 590], 
'Clackamas': [419, 425], 
'Clatsop': [39, 200], 
'Columbia': [51, 900], 
'Coos': [63, 275]}

或者: [float(item) for item in s.split(',')]將使每個值成為float

你可以用一個漂亮的單線做到這一點:

example = {
    'Baker': '16,765',
    'Benton': '93,590',
    'Clackamas': '419,425',
    'Clatsop': '39,200',
    'Columbia': '51,900',
    'Coos': '63,275'
}

new_dict = {k: [float(i) for i in v.split(',')]
            for k, v in example.items()}

# pretty print the output
from pprint import pprint
pprint(new_dict)

感謝您的回答。

這幫助我意識到我的主要問題是數字中的逗號。 我能夠使用example.replace(',','',regex=True)刪除源中的逗號

然后我能夠更改數據類型

convert_dict = {'column_name': int}
dataframe = dataframe.astype(convert_dict)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM