如何基于另一个数据框创建绘图新的数据框

时间:2020-04-12 09:32:27

标签: python pandas dataframe matplotlib plot

所以我有这种类型的数据框:

     Time  Type
1      81  sell
4       9  sell
7      36  sell
10     82   buy
13    106   buy
..    ...   ...
722   105  sell
723   105  sell
727   110  sell
728   110  sell
729   110  sell

时间显示星期几,类型显示动作(买或卖)。我想在多条图上绘制一个图表,其中X是从1-140开始的一周的小时数,Y是这段时间内的买卖数量。我该怎么办?

2 个答案:

答案 0 :(得分:0)

使用我的方法,我创建了两个用于买卖数量的新列,然后按时间和类型分组。然后我创建了一个情节。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df1=df.copy()
df1['Type_Count_Sell'] = np.where(df1['Type'] == 'sell', 1, 0)
df1['Type_Count_Buy'] = np.where(df1['Type'] == 'buy', 1, 0)
df1=df1.groupby(['Time', 'Type']).sum().reset_index()
#df1=df1.loc[df1.Time != '...']
df1['Time']=df1['Time'].astype(int)

ax = plt.subplot(111)
ax.set_title('Buys an dSells Count')
ax.set_xlabel('Hour')
ax.set_ylabel('Count of Type')
ax.bar(df1['Time'], df1['Type_Count_Sell'], width=1, color='b', align='center')
ax.bar(df1['Time']+1, df1['Type_Count_Buy'], width=1, color='g', align='center')
plt.show()

答案 1 :(得分:0)

如果我理解正确,

df.groupby(['Time']).apply(lambda x: x['Type'].value_counts()).plot(kind='bar')

或者如果您想要彼此相邻的小条。

df = df.groupby(['Time']).apply(lambda x: x['Type'].value_counts())
df.reset_index().pivot('Time','level_1','Type').plot(kind='bar')

enter image description here

相关问题