首页 > 解决方案 > 如何从终端绘制数据框?

问题描述

我的终端中有数据框作为输出。看起来像

2008Q1     503836
2008Q2     485872
2008Q3     686549
2008Q4     777268
2009Q1    1006589
2009Q2     849238
2009Q3     906675
2009Q4     973586
2010Q1    1090196
2010Q2    1029980
2010Q3     997876
2010Q4    1044607
2011Q1    1309266
2011Q2    1228180
2011Q3    1234710
2011Q4    1049315
2012Q1     716983
2012Q2     956271
2012Q3     788875
2012Q4     712312
2013Q1     658456
2013Q2     898281
2013Q3     822454
2013Q4     781709
2014Q1     854939
2014Q2     785794
2014Q3     724475
2014Q4     663736
2015Q1     746625
2015Q2     688598
2015Q3     633296
2015Q4     578003
2016Q1     603079
2016Q2     550575
2016Q3     482792
2016Q4     454369
2017Q1     490807
2017Q2     454263

该程序的运行时间很长,我忘记在代码末尾添加一个绘图命令。之后有没有办法绘制数据框?或者我可以保存数据框然后绘制它吗?

标签: pythonpandasdataframe

解决方案


Once the dataframe is printed out on the terminal and not saved you cannot plot it naturally in some way.

Since you said, you have a long runtime and presumably do not want to run the code again, you can copy the console output as you pasted it in your question and paste and save it in a *.txt file my_txt.txt. That file can easily be read by pandas without any manual changes of the format (assuming that the format in the question is exactly the one of the console)

>>> import pandas as pd
>>> a = pd.read_csv(r'L:\Stackoverflow\my_txt.txt', delim_whitespace=True, header=None, names=['A', 'B'])

>>> a.plot(x='A', y='B')    # You can e.g. plot the second column vs. the first one

This givesenter image description here


推荐阅读