iterate over columns to plot a graph of output data

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



iterate over columns to plot a graph of output data



I have written a small python script that plots a graph of my data. I wanted to modify the y variable such that I do not have to change the usecols=range(1,11) parameter every time my input changes. Is it possible to define a for loop within the np.gefromtxt function?


import numpy as np
import matplotlib.pyplot as plt
x = np.genfromtxt('classdist.csv', usecols=(0))
y = np.genfromtxt('classdist.csv', usecols=range(1,11))
y1 = y * 100
print ' x=', x, 'nn y=', y1
plt.plot(x, y1, linewidth =2)
plt.show()




2 Answers
2



You wouldn't usually call genfromtxt twice. But rather select what you need from the return.


genfromtxt


A = np.genfromtxt(..)
x = A[:,0]
y = A[:,1:]





Thank you for your Ernest answer kind Sir! ;)
– Pranav Shah
Aug 8 at 19:43



Like the previous answer suggested, the best course of action is probably to read the entire csv in first, then slice the first column as x, and the remaining as y. That way, as long as the first column in the csv is x, the script will work.



For a bit more nuanced solution, you can look into pandas as it supports named columns. Here is a very simple solution using pandas. There are a lot more you can do with it and it has better methods to work with tabular data.


import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("/path/filename.csv") #Read in the entire csv as a Dataframe object
x = df.iloc[:,0] #select the first column to be x. Here, you can also mention the column name like df["your_col_name"]
y = df.iloc[:,1:] #Select the rest to be y
y1 = y * 100
print ' x=', x, 'nn y=', y1
plt.plot(x, y1, linewidth =2)
plt.show()





Thanks Dipan. :)
– Pranav Shah
Aug 8 at 19:43






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard