0

次のようなデータを含むCSVファイルがあります

350, -0.042447984
349, -0.041671798
348, -0.04158416
347, -0.041811798
346, -0.041716855

私はもっ​​と多くのデータを持っていますが。私がやろうとしているのは、最初の列 (350、349 など) を x 値として定義し、2 番目の列 (-0.042447984、-0.041671798 など) を y 値として定義することです。これまでの私のコードは次のとおりです。

import pylab
x=[350, 349, 348, 347, 346]
y=[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]
pylab.plot(x, y)
pylab.show()

ただし、数値を手動で入力する代わりに、CSV ファイルから列 1 を x 値として抽出し、列 2 を y 値として抽出するプログラムを作成しようとしています。おそらく、私が作ろうとしているよりもはるかに簡単なものです。私はpythonが初めてなので、我慢してください!

4

3 に答える 3

2

あなたのcsvファイルがあなたが説明した形式であると仮定すると、おそらくloadtxt.

>>> d = numpy.loadtxt("plot1.csv", delimiter=",")
>>> d
array([[  3.50000000e+02,  -4.24479840e-02],
       [  3.49000000e+02,  -4.16717980e-02],
       [  3.48000000e+02,  -4.15841600e-02],
       [  3.47000000e+02,  -4.18117980e-02],
       [  3.46000000e+02,  -4.17168550e-02]])

xそして、これから取得する方法はたくさんありますy

>>> x,y = numpy.loadtxt("plot1.csv", delimiter=",", unpack=True)
>>> x
array([ 350.,  349.,  348.,  347.,  346.])
>>> y
array([-0.04244798, -0.0416718 , -0.04158416, -0.0418118 , -0.04171685])

またはx,y = d.Tまたはd[:,0], d[:,1]など

フォーマットが複雑になればなるほど、csvモジュールを直接操作したほうがよいでしょう。loadtxt多くのオプションがありますが、多くの場合、提供されるよりも細かい制御が必要です。

于 2012-07-27T19:00:59.463 に答える
1

これで始められます:

import csv

with open('data.txt') as inf:
    x = []
    y = []
    for line in csv.reader(inf):
        tx, ty = line
        x.append(int(tx))
        y.append(float(ty))

リストx、およびyそれぞれが含まれます:

[350, 349, 348, 347, 346]
[-0.042447984, -0.041671798, -0.04158416, -0.041811798, -0.041716855]

:

を使用withしてファイルを開くと、処理が完了したとき、または例外が発生したときにファイルを閉じることができます。csvモジュールは、入力データを 1 行ずつ読み取り、各行をカンマ区切りに基づいてリストに分割します。最初の項目は に変換されint、2 番目の項目はfloatそれぞれのリストに追加される前に に変換されます。

ファイルdata.txtにはサンプル データが含まれています。

于 2012-07-27T18:55:19.240 に答える
1

この投稿がかなり古いことは知っています。ただし、csv データをすばやくプロットする必要がある場合は、次のスクリプトが適切なソリューションを提供します。

csv ファイルからデータをインポートする方法と、png を作成してプロットする matplotlib を使用してプロットを作成する方法を示します。

ヘッダーなしでヒューロン湖のデータを使用すると、すばらしいプロットが得られます。

import csv
import matplotlib.pyplot as plt
from numpy import arange

#####################################
# instatiation of variables

filehandle = "lake_huron.csv"
x_data = []                         # makes a list
y_data = []                         # makes a list
png_filename = 'LakeData.png'

#####################################
# opening csv file and reading

my_file = open(filehandle, "rb")    # opens file for reading
data = csv.reader(my_file)          # saves file to variable "data"

#####################################
# saves csv data to x_data and y_data

for row in data:
    x_data.append(eval(row[1]))     # selects data from the ith row
    y_data.append(eval(row[2]))     # selects data from the ith row

#####################################
# closes csv file
my_file.close()                     # closes file




#####################################
# makes plot (show) and saves png

fig = plt.figure()                  # calls a variable for the png info

# defines plot's information (more options can be seen on matplotlib website)
plt.title("Level of Lake Huron from 1875 to 1972")      # plot name
plt.xlabel('Year')                                      # x axis label
plt.ylabel('Lake Level (in feet)')                      # y axis label
plt.xticks(arange(1875,1973,10))                        # x axis tick marks
plt.axis([1875,1973,573,584])                           # x and y ranges

# defines png size
fig.set_size_inches(10.5,5.5)                           # png size in inches

# plots the data from the csv above
plt.plot(x_data,y_data)

#saves png with specific resolution and shows plot
fig.savefig(png_filename ,dpi=600, bbox_inches='tight')     # saves png
plt.show()                                                  # shows plot

plt.close()                                                 # closes pylab
于 2015-10-01T03:58:21.740 に答える