我有一个文本文件,其中包含许多列和行以及各种数据类型。我想在python中读取文件并通过选择列来绘制值。我的文件如下所示:
time column1 column2 column3 column4 column5 column6 column7
100.035 6.667252E+00 -4.106210E+00 -1.577542E-02 4.090584E+00 -3.699584E-01 -6.998253E-02 -6.699544E-01
100.075 6.776713E+00 -4.347899E+00 -1.791951E-02 4.329726E+00 -3.699584E-01 -6.998253E-02 -6.699544E-01
100.115 6.806808E+00 -4.451121E+00 -1.886022E-02 4.432934E+00 -3.699584E-01 -6.998253E-02 -6.699544E-01
100.155 6.826516E+00 -4.534202E+00 -1.924360E-02 4.513488E+00 -3.699584E-01 -6.998253E-02 -6.699544E-01
100.195 6.890967E+00 -4.962194E+00 -1.946191E-02 4.943943E+00 -3.699584E-01 -6.998253E-02 -6.699544E-01
100.235 6.961544E+00 -5.430468E+00 -1.924892E-02 5.409640E+00 -3.699584E-01 -6.998253E-02 -6.699544E-01
我试着阅读作为中提到的文件在这里,并在这里,也尝试了一些基于模式分隔为代码在这里。到目前为止,下面代码的输出中所有列的位置都局限在first_columns
如清单1所示的位置values
。
import csv
with open ('mps50.txt', 'r') as f:
first_column = [row[0] for row in csv.reader(f,delimiter='\t')]
但这first_column
是一个列表,我想不出如何进一步使用它来帮助我绘制值。您能指导我如何做吗?一些示例或链接会有所帮助。
pandas
:pandas.read_csv
读取数据
txt
文件中显示的数据以空格作为分隔符,如图所示。matplotlib
到情节import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test.txt', sep='\\s+')
# df view
time column1 column2 column3 column4 column5 column6 column7
100.035 6.667252 -4.106210 -0.015775 4.090584 -0.369958 -0.069983 -0.669954
100.075 6.776713 -4.347899 -0.017920 4.329726 -0.369958 -0.069983 -0.669954
100.115 6.806808 -4.451121 -0.018860 4.432934 -0.369958 -0.069983 -0.669954
100.155 6.826516 -4.534202 -0.019244 4.513488 -0.369958 -0.069983 -0.669954
100.195 6.890967 -4.962194 -0.019462 4.943943 -0.369958 -0.069983 -0.669954
100.235 6.961544 -5.430468 -0.019249 5.409640 -0.369958 -0.069983 -0.669954
# all columns
plt.plot(df['time'], df.iloc[:, 1:], marker='o')
plt.xticks(rotation=90)
plt.show()
# specific column
plt.plot(df['time'], df['column1'], marker='o')
plt.xticks(rotation=90)
plt.show()
seaborn
import seaborn as sns
# set the index
df_ind = df.set_index('time')
sns.lineplot(data=df_ind, dashes=False, markers=True)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.xticks(rotation=90)
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句