Aman_X
Aman_X

Reputation: 87

Extract and plot data from a file in python

I have some data stored in a file (xyz.dat) in the following format:

1   0.997790664988225E+000   0.100177762164687E+001   0.100034262755073E+001        
2   0.997788473973293E+000   0.100177969047903E+001   0.100034273413754E+001        
3   0.997782981718032E+000   0.100178486093194E+001   0.100034301665219E+001

What I want to do is, for each row, store the first column as x and rest of the values as y[1], y[2], y[3]...so on. Later I want to plot the data stored in y[n] for each row separately. I am new to python and have tried using split() but did not have much success. I am either not able to separate out the first column or at the end of each row there is a trailing '\n'. Any help will be really appreciated. Thanks in advance.

Upvotes: 2

Views: 1050

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

You could read and plot as follows:

import matplotlib.pyplot as plt
import pandas as pd 

df = pd.read_csv('xyz.dat', sep=' ', header=None, usecols=(1, 2, 3)).T
df.plot(lw=0.5)
plt.show()

This would give you output:

matplotlib output

Your 3 rows contain very similar data.


If the number of columns is unknown, you could just read it in normally and drop the first CSV column (actually first row after being transposed):

df = pd.read_csv('xyz.dat', sep=' ', header=None).T.drop(0)
df.plot(lw=0.5)
plt.show()    

Upvotes: 1

quest
quest

Reputation: 3926

You can try:

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_fwf('file.dat')
plt.plot(df.iloc[:, 0], df.iloc[:,1])
plt.show()

You can go about plotting in the manner shown above. Hope this helps.

Upvotes: 0

Related Questions