简体   繁体   English

绘制/绘制此 csv 文件

[英]Plot/graph this csv file

I'm completely new to Python and decided to learn it for our machine learning course as an engineer, however I'm having difficulties in retrieving values from my csv file which looks like the following:我对 Python 完全陌生,并决定作为工程师在我们的机器学习课程中学习它,但是我在从我的 csv 文件中检索值时遇到了困难,如下所示:

在此处输入图片说明

Where I want to retrieve my B,C, and D values (retrieved from a Gravity sensor).我想在哪里检索我的 B、C 和 D 值(从重力传感器检索)。

Code I've tried in my Jupyter Notebook:我在 Jupyter Notebook 中尝试过的代码:

import numpy as np    
import matplotlib.pyplot as plt
    
data_file = np.genfromtxt("Gravity.csv", delimiter="", names=["A","B","C","D"])
    
plt.plot(data_file['A'], data_file['B'],data_file['C'],data_file['D'])    
plt.show()

I converted your file to this format我将您的文件转换为这种格式

A,B,C,D

0.1, 0.5, 0.1, 0.8

0.2, 0.1, 0.4, 0.1

0.1, 0.3, 0.1, 0.1 

and used the following code并使用以下代码

import pandas as pd
values= pd.read_csv('./test.csv')

this works这有效

在此处输入图片说明

I think your problem is that np.genfromtxt is also encoding the index column (values from 1 to 9) and also the header so that when you think you are selecting column 'B' you are actually selecting column A and so on.我认为您的问题是np.genfromtxt也在对索引列(值从 1 到 9)以及标题进行编码,因此当您认为您选择列'B'您实际上是在选择列A等等。

this should work这应该有效

import numpy as np    
import matplotlib.pyplot as plt
    
data_file = np.genfromtxt("Gravity.csv", delimiter=",", names=["index", "A","B","C","D"], skip_header=1)
    
plt.plot(data_file['B'],data_file['C'],data_file['D'])    
plt.show()

and a working example of the same concept but with artificial data以及相同概念但使用人工数据的工作示例

import pandas as pd
data = pd.DataFrame({'a':[1,2,3], 'b':[2,3,4], 'c':[4,5,6], 'd':[7,8,9]})
data.to_csv('./data.csv')
data2 = np.genfromtxt('./data.csv', delimiter=",", names=["index", "A","B","C","D"], skip_header=1)
plt.plot(data2['B'], data2['C'], data2['D'])
plt.show()

You have four columns in your data ( A , B , C , and D ) but you're only supplying three column names ( B , C , and D ).您的数据中有四列( ABCD ),但您只提供了三个列名( BCD )。 So it's linking name B to column A in the data and so on.因此,它将名称B链接到数据中的A列,依此类推。 Column D in the data is ignored like this so you need to designate four names so that each column can be queried as you expect.数据中的D列会像这样被忽略,因此您需要指定四个名称,以便可以按预期查询每一列。

Additionally, columnar data is handled well using pandas .此外,使用pandas可以很好地处理柱状数据。

import pandas as pd
    
data_file = pd.read_csv("Gravity.csv", names = ['A', 'B', 'C', 'D'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM