如何从.csv文件中提取数据并创建绘图?

2024-09-30 12:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.csv文件,有24列514行的数据。每一列都代表不同的参数,我希望研究不同参数之间的趋势。在

我使用genfromtxt将数据作为numpy数组导入,这样我就可以绘制两个特定列的值(例如,第9列对第11列)。以下是我目前所掌握的情况:

import matplotlib.pyplot as plt
import numpy as np


data = np.genfromtxt('output_burnin.csv', delimiter=',')

impactparameter=data[:,11]
planetradius=data[:,9]

plt.plot(planetradius,impactparameter,'bo')

plt.title('Impact Parameter vs. Planet Radius')
plt.xlabel('R$_P$/R$_Jup$')
plt.ylabel('b/R$_star$')

plt.show()

使用此代码,我在第12行遇到一个错误:

^{pr2}$

这里有什么问题?在

另外,我一直在试图找出如何在.csv文件中给每个列一个标题。因此,在绘制时,我可以直接调用特定列的名称,而不是计算列的编号。有办法吗?在

我是一个完全的Python新手,任何帮助都将不胜感激,谢谢!在


Tags: 文件csv数据importnumpydata参数as
1条回答
网友
1楼 · 发布于 2024-09-30 12:22:24

Also, I have been trying to figure out how to give each column a header in the .csv file. So instead of counting the column number, I can just call the name of that particular column when I do the plotting. Is there a way to do this?

要给数组名称中的列,需要使其成为structured array。在

下面是一个简单的例子:

a = np.zeros(5, dtype='f4, f4, f4')
a.dtype.names = ('col1', 'col2', 'col3')
print a[0]  # prints [0, 0, 0], the first row (record)
print a['col1']  # prints [0, 0, 0, 0, 0], the first column

如果您在CSV文件的开头有列名,并在np.genfromtxt中设置names=True,那么Numpy将自动为您创建一个具有正确名称的结构化数组。在

相关问题 更多 >

    热门问题