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

标签 python csv numpy genfromtxt

我有一个包含 24 列 x 514 行数据的 .csv 文件。这些列中的每一列代表不同的参数,我希望研究不同参数之间的趋势。

我正在使用 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 行遇到错误:

    impactparameter=data[:,11]
IndexError: too many indices

这里可能有什么问题?

此外,我一直在尝试弄清楚如何在 .csv 文件中为每一列指定一个标题。因此,我可以在绘图时调用该特定列的名称,而不是计算列号。有办法做到这一点吗?

我是 Python 的新手,非常感谢任何帮助,谢谢!

最佳答案

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 会自动创建一个结构化数组你有正确的名字。

关于python - 如何从 .csv 文件中提取数据并创建绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637715/

相关文章:

python - 使用 Python 搜索并用双引号替换 csv 中的行

python - 如何将每个抓取的项目组织到 csv 行中?

python-3.x - 如何使用 scikit-learn 组合具有不同维度输出的特征

使用数据框列值的 Python Pandas 绘图

python - 多 GPU 训练中的损失函数 (PyTorch)

python - BeautifulSoup 为 .find 和 .find_all 提供不同的结果

mysql - 通过 MySQL Workbench 的 "Table Data Import Wizard"导入带有转义引号的 CSV 文件

python - 为什么在OpenCV中将laplacian转换为uint8?

python - 移动目录后 Django 无法工作。我有路径/Python 安装问题吗?

python - 我收到错误代码 "expected an indented block",但不知道为什么