How to convert a vector including number and character into numeric vector in python?

Viewed 25

Is there anyway to do this without using forloop?

Input: c("1","2","3","a")

Expected output: 'c(1,2,3,NA)

I am not familiar with python, so I use the format of R to describe the input and output.

1 Answers

try this

from math import nan

lst = ["1","2","3","a"]



lst = [int(a) if a.isdigit() else nan for a in lst]


print(lst)

output

[1, 2, 3, nan]
Related