按组和在特定值之间从数据帧绘制图形

2024-04-26 15:04:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个金融数据集,其中包含一些时间段内一些市场的指标。你知道吗

market  date    metric1    metric2    metric3
ASX     2000            
ASX     2001            
ASX     2002            
ASX     2003            
TSX     2000            
TSX     2001            
TSX     2002            
TSX     2003            
TSX     2004            
NYSE    2000            
NYSE    2001            
NYSE    2002            
NYSE    2003            
NYSE    2004    

Metric1到metric3包含数值。我想画一些线或条形图,根据市场和一些日期值进行分组,在这个例子中是2000年和2002年。我的日期变量可以是yearmonth(例如200101、200102)。有没有办法告诉python现在是yearmonth,所以200112和200201之间没有间隔? 我正在使用matplotlib和pandas。你知道吗


Tags: 数据date市场指标market金融时间段asx
2条回答

Is there a way to tell python that it is yearmonth so there is no gap between 200112 and 200201?

从你的描述听起来你可能在找pd.Series.between。你可以用它,例如

 df.date = pd.to_datetime(df.date) # "tell" pandas it is dates.

 df[df.date.between(pd.to_datetime('2011-01'), pd.to_datetime('2012'))]

如您所见,pd.to_datetime可以采用不同的格式(有时间和日期或没有)。还要注意,between有一个inclusive参数。你知道吗

I would like to draw some line or bar graphs that group by market and between some date values, say 2000 and 2002 in this example

在这两种情况下,我都将使用此作为我的数据:

import pandas as pd
import matplotlib.pyplot as plt    
df = pd.DataFrame({'market': ['A', 'A', 'B', 'B', 'C', 'C'],
                       'date': [2000, 2001, 2000, 2001, 2000, 2001], 
                       'm1': [1, 2, 3, 4, 5, 6 ],
                       'm2': [4, 3, 5, 2, 1, 0]})

使用@Ami Tavory's answer正确格式化日期

对于每个公制的一个子批次:

f, ax = plt.subplots(ncols=2)

df.pivot(columns='market', index='date', values='m1').plot(ax=ax[0])
df.pivot(columns='market', index='date', values='m2').plot(ax=ax[1])

plt.plot()

One subplot per metric

对于每个市场的一个子地块:

f, ax = plt.subplots(ncols=3)

df[df.market=='A'].plot(x='date', y=['m1', 'm2'], ax=ax[0])
df[df.market=='B'].plot(x='date', y=['m1', 'm2'], ax=ax[1])
df[df.market=='C'].plot(x='date', y=['m1', 'm2'], ax=ax[2])

plt.plot()

One subplot per market

相关问题 更多 >