[英]How to read data from a file with a nonstandard separator and plot the values
我有一个包含如下数字的 .txt 文件:
编号 --- 金额 -------- 地点
1 ----- 23.5 ----- -0.0039
3 ----- 2.093 -------- 0.992
7 ----- 1.211 -------- 0.3929
5 ----- 0.898 -------- -1.8933
等等
我有大约。 700 个号码。 现在我想 plot 并可视化这些数字。 确切地说:我想在 x 轴上显示“金额”,在 y 轴上显示“位置”。 该图应类似于正弦曲线。 此外,我想选择某些数字。 例如,只有1号和2号。也就是说,我需要读入1号和2号的金额和位置。
我以前从未使用过 Python 或 Matplotlib。 因为我希望有人可以帮助我或给我一些提示。
到目前为止,我有以下代码:
import matplotlib.pyplot as plt
import numpy as np
import io
numbers_file = open('numbers_file.txt').read().replace(',',' ')
numbers_data = np.loadtxt(io.StringIO(numbers_file),skiprows=1)
x = np.linspace(0, 2*np.pi, 20)
y = np.sin(x)
beta = x
plt.figure(figsize=(7,3))
plt.title('Companies amount and location')
plt.plot(x,y, label=r'sin( $\beta$ )')
plt.xlabel(r'$\beta$')
plt.ylabel('Location')
plt.legend()
plt.grid()
plt.show()
除此之外,我想使用一个特定的文本文件条目作为我的数据图的起点和终点。 一些条目(通过文本文件中的“编号”访问)应显示为最大值和最小值。
我会非常感谢我能得到的每一个帮助,因为我对如何解决这个问题有点迷茫。
pd.read_csv
创建一个pandas.DataFrmae
,它可以有一个正则表达式作为分隔符。
,
请不要指定sep
和engine
pandas.DataFrame.plot
绘制数据,它使用matplotlib
作为默认后端。EBselected = df[df['No.'].isin([1, 7])]
python 3.9.7
、 pandas 1.3.4
、 matplotlib 3.4.3
中测试import pandas as pd
# read the data in from the file
df = pd.read_csv('numbers_file.txt', sep=' -* ', engine='python')
# display(df)
No. Amount Location
0 1 23.500 -0.0039
1 3 2.093 0.9920
2 7 1.211 0.3929
3 5 0.898 -1.8933
# plot
ax = df.plot(x='Amount', y='Location')
ax = df.plot(kind='scatter', x='Amount', y='Location')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.