我有一个 CSV 文件,其中包含在几分钟内记录的随机传感器的数据。现在我想将该数据从 CSV 文件流式传输到我的 python 代码,就好像它直接从传感器本身接收数据一样。(代码用于从两个不同的传感器/csv 文件中获取读数并将它们平均。)有人建议使用 Apache Spark 来流式传输数据,但我觉得这对我来说有点太复杂了。可能有更简单的解决方案吗?
问问题
10224 次
3 回答
6
您还可以使用 pandas read_csv() 函数以小块读取大 csv 文件,基本代码如下所示:
import pandas as pd
chunksize = 100
for chunk in pd.read_csv('myfile.csv', chunksize=chunksize):
print(chunk)
这个链接解释了它是如何工作的:http: //pandas.pydata.org/pandas-docs/stable/io.html#io-chunking
于 2017-10-04T10:54:16.097 回答
0
您还可以在 Numpy/Matplotlib 上使用 Python。这是一种将 csv 数据临时作为变量而不是额外文件流式传输的简单方法。
´import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
import io
def draw_graph_stream(csv_content):
csv_stream = io.StringIO(csv_content)
svg_stream = io.StringIO()
data = np.genfromtxt(csv_stream, delimiter = ';') # generate the stream
x = data[0,:] #first row in csv
y = np.mean(data[1:,:], axis=0) # first column with mean generate the average
plt.plot(x,y)
plt.savefig(svg_stream, format = 'svg') #just safe it as svg
svg_stream.seek(0) #Position 0 for reading after writing
return svg_stream.read()
print("Start test")
with io.open('/filepathtodata','r') as csv_file: #works like a Loop
print("Reading file")
csv_content = csv_file.read()
print("Drawing graph")
svg_content = draw_graph_stream(csv_content)
with io.open('thefilepathforsafe','w+') as svg_file:
print("Write back")
svg_file.write(svg_content)´
于 2018-10-19T08:57:42.570 回答
0
你可以在 python 中使用类似的东西tail -f
来实现这一点。这应该做你想做的。http://lethain.com/tailing-in-python/
于 2017-01-17T18:55:30.567 回答