簡體   English   中英

如何在python中將字符串列表轉換為數組中的int列表

[英]How to convert from a list of string to a list of int in array in python

a= pd.DataFrame({"A": [['1','2'], '2','3']}).to_numpy()

我想得到a = {"A": [[1, 2], 2, 3]}我不能對數組中的列表使用 astype

 df.apply(lambda x: int(x), index=['A', ]), axis=1)

轉換是通過將字符串轉換為 int 來完成的,即'3'int('3')

你只是想從a = [['1', '2'], '2', '3']a = [[1, 2], 2, 3] ,還是大熊貓有點重要?

如果它是從您的熊貓起點開始,則以下內容有效。

import pandas as pd

# Starting point
a = pd.DataFrame({"A": [['1','2'], '2','3']})

# Iterate over rows in dataframe
for index, row in a.iterrows():
    # If row contains a list
    if isinstance(row[0], list):
        # Convert each entry in list from string to int
        a.loc[index, 'A'] = [int(val) for val in row[0]] 
    else: 
        a.loc[index, 'A'] = int(row)

a = a.to_dict(orient='list')
print(a)
# {'A': [[1, 2], 2, 3]}

如果你只是想從a = [['1', '2'], '2', '3']a = [[1, 2], 2, 3]

a = [['1', '2'], '2', '3']
a = [list(map(int, x)) if isinstance(x, list) else int(x) for x in a]
print(a)
# [[1, 2], 2, 3]

暫無
暫無

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

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