matplotlib 图表每月汇率

3pmvbmvn  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(159)

我从这个网站https://www.federalreserve.gov/releases/H10/hist/dat96_ja.txt的数据
我想画一个折线图,显示1997年和1998年的平均月利率。
所以x轴将是Jan 97,Feb 97,.....,Dec 98。
这就是我到现在为止所做的

import pandas as pd
usyen = pd.read_csv("usyen.csv")
usyen = usyen.iloc[6:]
usyen[['Date','Rate']] = usyen.Column1.str.split(expand=True)
usyen.reset_index(inplace=True)
usyen = usyen.drop(['Column1', 'Column2', 'index'], axis=1)
usyen

import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style = 'whitegrid')
fig, ax = plt.subplots(figsize = (10,5))

x = usyen(usyen.Date == 1997, 1998)['Date']
y = usyen['Rate']

ax.plot(x,y)

ax.set_title('Yen/US Exchange Rate')
ax.set_xlabel('Year')
ax.set_ylabel('Rate')

我的问题是图表没有显示出来。错误:“DataFrame”对象不可调用
先谢谢你了

ny6fqffe

ny6fqffe1#

关于您的错误:

x = usyen(usyen.Date == 1997, 1998)['Date']

要过滤 Dataframe ,应该使用[...]而不是(...)。要修复代码,请用途:

m = usyen['Date'].str.contains(r'-(97|98)$')  # ends with -97 or -98
x = usyen.loc[m, 'Date']
y = usyen.loc[m, 'Rate']

但是,您可以优化代码:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style = 'whitegrid')

# Read data
url = 'https://www.federalreserve.gov/releases/H10/hist/dat96_ja.txt'
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/112.0'}
df = pd.read_csv(url, skiprows=6, header=None, na_values='ND', names=['Date', 'Rate'], sep='\s+', engine='python', storage_options=hdr)
df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%y')

# Extract subset and plot
df1 = df[df['Date'].between('1997-01-01', '1998-12-31', inclusive='left')]
ax = df1.plot(x='Date', y='Rate', title='Yen/US Exchange Rate', legend=False)
plt.tight_layout()
plt.show()

输出:

相关问题