How to plot List data in csv file

Viewed 91

I am trying to plot 2 columns from a csv file. Each column contains list of values. How can I plot those columns. The columns are read as strings and unable to identify the "[" character.

Here's a snippet of my csv. I want to plot column1 versus column2 for all Names(A,B,C)

Name    Column1        column2          Column3 
A    [0.1,0.2,0.3]    [0.1,0.2,0.3]     0.2
B    [0.9,0.7,0.3]    [0.1,0.8,0.3]     0.2
C    [0.1,0.2,0.6]    [0.1,0.2,0.3]     0.2

I tried to use the following code

r = pd.read_csv('L.csv')
plt.plot(r.loc[i]['Column1'].astype(float),
             r.loc[i]['Column2'].astype(float),
             linestyle="--",
             label="{}, Led={:.3f}".format(i, r.loc[i]['Column3']))
2 Answers

You can use ast.literal_eval() function to convert string types to types present inside the string:

See more here

import ast
plt.plot(ast.literal_eval(r.loc[i]['Column1']),
             ast.literal_eval(r.loc[i]['Column2']),
             linestyle="--",
             label="{}, Led={:.3f}".format(i, r.loc[i]['Column3']))

I used your csv data to read the data in:

Name;Column1;Column2;Column3
A;[0.1,0.2,0.3];[0.1,0.2,0.3];0.2
B;[0.9,0.7,0.3];[0.1,0.8,0.3];0.2
C;[0.1,0.2,0.6];[0.1,0.2,0.3];0.2
df = pd.read_csv('input_csv.csv', sep=';')

#change the strings to actual lists
df[['Column1', 'Column2']] = df[['Column1', 'Column2']].applymap(ast.literal_eval)

#explode the list to seperate rows
out = df.explode(column=['Column1', 'Column2'])
print(out)

for grp, val in out.groupby('Name'):
    plt.plot(val['Column1'], 
             val['Column2'], 
             linestyle='--', 
             label="{}, Led={:.3f}".format(grp, val['Column3'].unique()[0]))
plt.legend()

Output of out:

  Name Column1 Column2  Column3
0    A     0.1     0.1      0.2
0    A     0.2     0.2      0.2
0    A     0.3     0.3      0.2
1    B     0.9     0.1      0.2
1    B     0.7     0.8      0.2
1    B     0.3     0.3      0.2
2    C     0.1     0.1      0.2
2    C     0.2     0.2      0.2
2    C     0.6     0.3      0.2

Plot: enter image description here

Related