Kyv
Kyv

Reputation: 677

How to access pandas data from a table

I am trying to read data using pandas. output test

Here is what I have tried:

df = pd.read_csv("samples_data.csv")
in_x = df.for_x
in_y = df.for_y
in_init = df.Init

plt.plot(in_x[0], in_y[0], 'b-')

The problem is that, in_x and in_y output a string: (0, '[5 3 9 4.8 2]') (1, '[6 3 9 4.8 2]') ... How could I solve the problem ?

Thank you for taking the time to answer my question.

I was expecting :

in_x_1 = in_x[2][0]  # output: [
in_x_2 = in_x[2][1]  # output: 6

Upvotes: 1

Views: 94

Answers (1)

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

Read in dataframe, and slice with the iloc method:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([
    [[5,3,9,4.8,2], [5,3,9,4.8,9], 33],
    [[6,3,9,4.8,2], [4,3.8,9,8,4], 87],
    [[6.08,2.89,9,4.8,2], [8,3,9,4,7.34], 93],
    ],
    columns=["for_x", "for_y", "Init"]
)

print(df)
in_x = df.for_x.iloc[0]
in_y = df.for_y.iloc[0]
plt.plot(in_x, in_y, 'b-')
plt.show()

Printing the dataframe:

                     for_x               for_y  Init
0        [5, 3, 9, 4.8, 2]   [5, 3, 9, 4.8, 9]    33
1        [6, 3, 9, 4.8, 2]   [4, 3.8, 9, 8, 4]    87
2  [6.08, 2.89, 9, 4.8, 2]  [8, 3, 9, 4, 7.34]    93

If your dataframe has string entries, the eval function will turn them into lists which you can then plot data from:

df_2 = pd.DataFrame([
      ['[5,3,9,4.8,2]', '[5,3,9,4.8,9]', 33],
      ['[6,3,9,4.8,2]', '[4,3.8,9,8,4]', 87],
      ['[6.08,2.89,9,4.8,2]', '[8,3,9,4,7.34]', 93],
      ],
      columns=["for_x", "for_y", "Init"]
)

in_x = eval(df_2.for_x.iloc[0])
in_y = eval(df_2.for_y.iloc[0])

If your values are not comma separated:

df_3 = pd.DataFrame([
      ['[5 3 9 4.8 2]', '[5 3 9 4.8 9]', 33],
      ['[6 3 9 4.8 2]', '[4 3.8 9 8 4]', 87],
      ['[6.08 2.89 9 4.8 2]', '[8 3 9 4 7.34]', 93],
      ],
      columns=["for_x", "for_y", "Init"]
)

string_of_nums_x = df_3.for_x.iloc[0].strip('[').strip(']')
in_x = [float(s) for s in string_of_nums_x.split()]

string_of_nums_y = df_3.for_y.iloc[0].strip('[').strip(']')
in_y = [float(s) for s in string_of_nums_y.split()]

Plotting: enter image description here

Upvotes: 1

Related Questions