Pandas dataframe convert to Array

using Pandas
using Plots: plot

df = read_table("M.out/table.txt")

x = Array(df["# t (s)"])

plot(x,  Array(df["mx ()"]))
plot!(x, Array(df["my ()"]))
plot!(x, Array(df["mz ()"]))

In this code is there a way to reconstruct df so I don’t have to wrap an Array constructor every time?

I mean how to make something like this work: plot(x, df["mx ()"])

Thanks in advance!

Do you have to use pandas? Why not DataFrames?

1 Like

My table.txt file is a simulation file it writes like this:

# t (s)	mx ()	my ()	mz ()	E_total (J)
1e-09	0.9999239	0.008726204	0	-1.5230464e-14
2e-09	0.9996954	0.017449748	0	-6.091727e-14
3e-09	0.9993148	0.02616798	0	-1.3704653e-13

and in the headers there is a space between the mx and parenthesis, mx (), so I didn’t know what delimiter to use there, del = " " doesn’t work. Actually, I haven’t spent much time in DataFrames since Pandas works perfectly in this situation.

This hack should let you automatically convert to Array without type piracy, but @nilshg 's answer may be the most idiomatic solution.

using Pandas
using Plots: Plots
plot(args...; kw...) = Plots.plot(Array.(args)...; kw...)
plot!(args...; kw...) = Plots.plot!(Array.(args)...; kw...)

df = read_table("M.out/table.txt")

x = df["# t (s)"]

plot(x,  df["mx ()"])
plot!(x, df["my ()"])
plot!(x, df["mz ()"])

plot(1:10, sin.(1:10), title="normal usage still works")
1 Like

Thanks @Lilith! That’s what I was looking for!!

But anyways I found a more neat way by using DataFrames as @nilshg suggested:

using DataFrames, CSV
using Plots

df = DataFrame(CSV.File("makale.out/table.txt"))

x = df[!, "# t (s)"]

plot(x,  df[!, "mx ()"])
plot!(x, df[!, "my ()"])
plot!(x, df[!, "mz ()"])

Thank you both for your quick reply!