【问题标题】:Plotting selected values from txt file in python在python中从txt文件中绘制选定的值
【发布时间】:2018-09-24 12:18:13
【问题描述】:

我有一个 txt 文件,其中包含对应于 2016-2018 年每一天的每一秒的数据(每天结束大约 1400 多个数据),首先,我选择了特定日期的数据:05.01.2016,然后我想使用当天的数据在 python 中绘制图表

以下代码用于选择值和绘制图形:

if '01.05.2016' in row: #select the value in day 05.01.2016
    x = [row.split()[6]] 
    y = [row.split()[2]]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x,y)
plt.ylim((200,800))
plt.show()

如果我使用命令:

x = [row.split()[6]] 
y = [row.split()[2]]
print(x,y)

那么 x 和 y 就会成功出来(只是一些 x-y 值作为例子):

['01.05.2016/15:43:00'] ['499']
['01.05.2016/15:44:00'] ['501']
['01.05.2016/15:45:00'] ['502']
['01.05.2016/15:46:00'] ['502']

我原来的 txt.file 的一部分是这样的:

01.05.2016  15:43:00    499 U   42491,65486  -0,01   01.05.2016/15:44:00
01.05.2016  15:44:00    501 U   42491,65556  0,01   01.05.2016/15:45:00 
01.05.2016  15:45:00    502 U   42491,65625  0,02   01.05.2016/15:46:00 
01.05.2016  15:46:00    503 U   42491,65694  0,03   01.05.2016/15:47:00 

但是如果我继续写绘制图​​形的命令。该图只显示一对(最后一对)x-y 值,我的图是这样的:

谁能帮帮我?

【问题讨论】:

  • 你想只绘制上面列出的 4 个 x-y 值吗?
  • @Bazingaa 感谢您的回复。不,这 4 行只是示例,实际上在 01.05.2616 中大约有 1400 个 x-y 值,我想要全部作为我的 x-y 值。
  • 那么告诉我们你目前得到的数字是多少?很难想象你的问题可能是什么
  • @It'sNele 使用这个:df['time'] = pd.to_datetime(df['time'], format='%d.%m.%Y/%H:%M :%S')
  • @Joe OMG,效果很好,非常感谢!!! :)))))))))))))))))))))

标签: python pandas dataframe matplotlib


【解决方案1】:

你可以这样做:

import matplotlib.pyplot as plt
df = pd.read_csv('file.txt', sep = '\t', names = ["col", "col1", "val", "col3", "col4", "time"])
df['time'] = pd.to_datetime(df['time'], format='%d.%m.%Y/%H:%M:%S')
df.set_index('time', inplace=True)
match_timestamp = "01.05.2016"
df1 = df.loc[df.index.strftime("%m.%d.%Y") == match_timestamp]
print df1
df1['val'].plot()
plt.show()

注意pd.read_csv中的分隔符

示例

输入:

01.04.2016  15:46:00    503 42491,65694 0,03    02.05.2016/15:47:00
01.05.2016  15:43:00    499 42491,65486 -0,01   01.05.2016/15:44:00
01.05.2016  15:44:00    501 42491,65556 0,01    01.05.2016/15:45:00 
01.05.2016  15:45:00    502 42491,65625 0,02    01.05.2016/15:46:00 
01.05.2016  15:46:00    503 42491,65694 0,03    01.05.2016/15:47:00 
02.05.2016  15:46:00    503 42491,65694 0,03    02.05.2016/15:47:00

df1:

                            col      col1   val         col3   col4
time                                                               
2016-01-05 15:44:00  01.05.2016  15:43:00   499  42491,65486  -0,01
2016-01-05 15:45:00  01.05.2016  15:44:00   501  42491,65556   0,01
2016-01-05 15:46:00  01.05.2016  15:45:00   502  42491,65625   0,02
2016-01-05 15:47:00  01.05.2016  15:46:00   503  42491,65694   0,03

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2021-06-23
    • 2020-12-17
    • 1970-01-01
    相关资源
    最近更新 更多