簡體   English   中英

將列表元素的類型從numpy.int64更改為int

[英]Change type of list elements from numpy.int64 to int

{
    "key1" : <list of strings>,
    "key2" : <list of integeres> }

我想將“ key2”列表的類型更改為int。 我已經嘗試過循環使用

v =整數(v)

我也嘗試將int映射到整個列表。

map(int,list)

還有其他方法可以完成此任務嗎?

當前代碼:

integer_columns = ["col1","col2","col3","col4"]
for col in integer_columns:
    col_list = config_data[col]
    col_list = list(map(int, col_list))

map怎么了?

在Python 3上d['key2'] = list(map(int, d['key2'])) d['key2'] = map(int, d['key2'])d['key2'] = list(map(int, d['key2']))

d = {'key2': ['1', '2', '3']}
print(d)
d['key2'] = list(map(int, d['key2']))
print(d)

輸出

{'key2': ['1', '2', '3']}
{'key2': [1, 2, 3]}

OP更新問題后進行編輯

for col in integer_columns:
    col_list = config_data[col]          # col_list references to config_data[col]

    col_list = list(map(int, col_list))  # now col_list references to an entire
                                         # new list of ints, that has nothing to do
                                         # with config_data[col]

col_list正在修改,但此更改不會反映回col_list config_data[col] 相反,請執行與上述原始答復中所示類似的操作:

for col in integer_columns:
    config_data[col] = list(map(int, config_data[col]))

錯誤修復。

假設您有一個字典,每個鍵都映射到numpy.int64列表。

設定

d = {'key2':[np.int64(v) for v in xrange(10)]}

試用版

%timeit -n 1000 d['key2'] = map(int, d['key2'])
1000 loops, best of 3: 1.5 µs per loop

%timeit -n 1000 d['key2'] = [int(v) for v in d['key2']]
1000 loops, best of 3: 2.0 µs per loop

%timeit -n 1000 d['key2'] = [np.asscalar(v) for v in np.array(d['key2'])]
1000 loops, best of 3: 11.6 µs per loop

用您當前的代碼更新:

integer_columns = ["col1","col2","col3","col4"]  # assuming you have a list of list here

for col in integer_columns:
    x = np.array(col)
    config_data[col] = [np.asscalar(v) for v in x]

# >>> type(integer_columns[0][1])
# >>> int

numpy.asscalar是numpy中的一個函數,用於將numpy類型轉換為本機python類型。 這是解釋它的好答案

因此,肯定還有其他方法,這取決於您特定方案的特定解決方案。

暫無
暫無

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

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