【问题标题】:How to check if an element string in a numpy array can be changed into an integer and if so, change it? python如何检查numpy数组中的元素字符串是否可以更改为整数,如果可以,更改它? Python
【发布时间】:2021-06-02 11:15:40
【问题描述】:

如果我有一个包含字符串的列表或 numpy 数组,如何检查元素是否为数字,如果是,将它们更改为整数并替换它们?

list1 = [["australia", "1", "5000, "red"], ["canada", "4", "412", "green"],...]
list1 = np.asarray(list1)

k = 0
for item in list1:
   j = 0
   for element in item:
      if element.isnumeric():
          list1[k][j] = int(element)
      j = j + 1
   k = k + 1

但它没有给我输出:

[["australia" 1  5000 "red"], ["canada" 4 412 "green"],...]

【问题讨论】:

  • 您是否期望输出是一个 numpy 数组?

标签: arrays python-3.x numpy


【解决方案1】:

你可以用 1 行来完成:

list1 = [[int(x) if x.isnumeric() else x for x in lst] for lst in list1]

【讨论】:

  • 这个输出给了我:[['a', 'u', 's', 't', 'r'', 'a', 'l', 'i', ' a'] , [1], [5000], ['r', 'e', 'd']......
  • print(list1) 输出为:[['australia', 1, 5000, 'red'], ['canada', 4, 412, 'green']]
  • 哦,是的,抱歉,我一定是打印了别的东西……非常感谢!!
  • 注意到它适用于列表但不适用于 numpy 数组。
  • 有没有办法让它与 numpy 数组一起工作
【解决方案2】:

我在我的机器上运行它,你的代码有效。

list1 = [["australia", "1", "5000", "red"], ["canada", "4", "412", "green"]]
#list1 = np.asarray(list1)

k = 0
for item in list1:
   j = 0
   for element in item:
      if element.isnumeric():
          list1[k][j] = int(element)
      j = j + 1
   k = k + 1
  
print(list1)

输出是

[['australia', 1, 5000, 'red'], ['canada', 4, 412, 'green']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-27
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2013-09-19
    相关资源
    最近更新 更多