2
votes

Imagine I have a dataframe

df=DataFrame(A=rand(5),B=["8", "9", "4", "3", "12"])

What I want to do is to convert column B to Int type, so I used

df[!,:B] = convert.(Int64,df[!,:B])

But I got warning:

'Cannot Convert an object of type string to an object of type Int64'

Could you please tell me why I was wrong?

2
Note that it is enough to write df.B instead of df[!, :B] here and in the answers. - Bogumił Kamiński

2 Answers

3
votes

What you are looking for is the parse function, broadcast over the elements in the column with dot notation:

df = DataFrame(A = rand(5), B = ["8", "9", "4", "3", "12"])
df[!, :B] = parse.(Int64, df[!, :B])
1
votes

I believe what you want is df[!,:B] = Int64.(df[!,:B]). Convert is only defined between types where you can convert without losing information (ie in this case, you can't convert an arbitrary string to an Int)