【问题标题】:Plotting in Python extracting only specific columns from a CSV在 Python 中绘图,仅从 CSV 中提取特定列
【发布时间】:2017-06-20 16:32:51
【问题描述】:

编辑:建议缩短问题:

对 python 和编程很陌生,我想将第 1 列和第 4 列绘制成 log(x) log(y) 图表。老实说,我不知道如何从中只提取我需要的两列。

16:58:58 | 2.090 | 26.88  | 1.2945E-9  |   45.8
16:59:00 | 2.031 | 27.00  | 1.3526E-9  |  132.1
16:59:02 | 2.039 | 26.90  | 1.3843E-9  |  178.5
16:59:04 | 2.031 | 26.98  | 1.4628E-9  |  228.9
16:59:06 | 2.031 | 27.04  | 1.5263E-9  |  259.8
16:59:08 | 2.027 | 26.84  | 1.6010E-9  |  271.8

【问题讨论】:

  • 使用pandas 库将大大简化您的生活!
  • 欢迎来到 SO:请拨打tour。你应该把这两个问题分成两个单独的问题。首先,也许您希望以正确的形状获取数据。然后你要担心绘制它。
  • @nbeuchat 到目前为止检查它看起来不错。
  • @ShawnMehan 完成
  • 尤其是 16 点钟的对数。

标签: python python-3.x csv matplotlib


【解决方案1】:

使用熊猫:

import pandas as pd
df = pd.read_csv("data.txt", delimiter="\s[|]\s+", header=None, index_col=0)
df.plot(y=4)

(请注意,这忽略了对数缩放,因为不清楚时间的对数应该是什么)

【讨论】:

  • 嘿嘿抱歉,我没有评论时间日志,因为我认为这是一个笑话。 Log 不是 16 点的,而是将其转换为 [s] 中的 $\Delta t$,然后是 $log(\Delta t)$。但我认为我可以做到这一步。
【解决方案2】:

如果你不想使用优秀的pandas,这里有一个steam方法。

import matplotlib.pyplot as plt
import math
import datetime as dt

test = """16:58:58 | 2.090 | 26.88  | 1.2945E-9  |   45.8\n
16:59:00 | 2.031 | 27.00  | 1.3526E-9  |  132.1\n
16:59:02 | 2.039 | 26.90  | 1.3843E-9  |  178.5\n
16:59:04 | 2.031 | 26.98  | 1.4628E-9  |  228.9\n
16:59:06 | 2.031 | 27.04  | 1.5263E-9  |  259.8\n
16:59:08 | 2.027 | 26.84  | 1.6010E-9  |  271.8\n"""

lines = [line for line in test.splitlines() if line != ""]

# Here is the real code
subset = []

for line in lines:
    parts = line.split('|')
    ts = dt.datetime.strptime(parts[0].strip(), "%H:%M:%S")
    num = math.log(float(parts[3].strip()))
    subset.append((ts, num))

# now there is a list of tuples with your datapoints, looking like
# [(datetime.datetime(1900, 1, 1, 16, 58, 58), 1.2945E-9), (datetime.datetime(1900, 1, 1, 16, 59), ...]
# I made this list intentionally so that you can see how one can gather everything in a tidy way from the
# raw string data.

# Now lets separate things for plotting
times = [elem[0] for elem in subset]
values = [elem[1] for elem in subset]

# now to plot, I'm going to use the matplotlib plot_date function.
plt.figure()
plt.plot_date(times, values)
# do some formatting on the date axis
plt.gcf().autofmt_xdate()
plt.show()

【讨论】:

  • 我不确定lines = [line for line in test.splitlines() if line != ""] 做了什么
  • 它不会影响您的解决方案。它是一种将测试数据块转换为模仿文件中读取行的格式的机制。您只需要担心real code 下方的评论。也就是说,它会从 test 字符串生成行列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多