【问题标题】:How to plot data in pandas by date and perform grouping at the same time如何按日期在熊猫中绘制数据并同时执行分组
【发布时间】:2014-05-02 18:56:42
【问题描述】:

我经常发现自己想在一列中逐列绘制数据,但发现很难按第三列对它们进行分组/分隔。

假设我有一张这样的表格

如何在 pandas 中创建相同的情节?

顺便说一句:我喜欢 x 轴是线性的,而不仅仅是一组彼此相邻对齐的日期,因为它提供并了解一组内的测量值彼此之间的接近程度 - 但很高兴知道距离太远怎么办。

更新

@Ffisegydd 的回答非常有用。但是,我接受答案的速度有点太快了——我在实际的 Excel 工作表上尝试代码时发现了这一点。这个问题完全是我的错,因为我没有提供 Excel 表格。 @Ffisegydd 非常乐意根据我的问题手动创建数据框,但是使用 excel 文件有点不同。

我确实道歉。这是一个Excel文件: https://dl.dropboxusercontent.com/u/3216968/Example.xlsx

这是我走了多远(在 IPython 笔记本中)

import pandas as pd
import datetime as dt

path2file = r"C:\Example.xlsx"
_xl = pd.ExcelFile(path2file)
df = pd.read_excel(path2file, _xl.sheet_names[0], header=0)
df

df.Date = df.Date.apply( lambda x: dt.datetime.strptime(x, '%Y.%m.%d').date() )
df

这里出了问题:

pd.DataFrame( data= [df.Data, df.Group], columns = ['Data', 'Group'], index=df.Date)

给出这个错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-231baa928f67> in <module>()
----> 1 pd.DataFrame( data= [df.Data, df.Group], columns = ['Data', 'Group'], index=df.Date)

C:\Python27\lib\site-packages\pandas\core\frame.pyc in __init__(self, data, index, columns, dtype, copy)
    245                         index = _default_index(len(data))
    246                     mgr = _arrays_to_mgr(arrays, columns, index, columns,
--> 247                                          dtype=dtype)
    248                 else:
    249                     mgr = self._init_ndarray(data, index, columns, dtype=dtype,

C:\Python27\lib\site-packages\pandas\core\frame.pyc in _arrays_to_mgr(arrays, arr_names, index, columns, dtype)
   4471     axes = [_ensure_index(columns), _ensure_index(index)]
   4472 
-> 4473     return create_block_manager_from_arrays(arrays, arr_names, axes)
   4474 
   4475 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in create_block_manager_from_arrays(arrays, names, axes)
   3757         return mgr
   3758     except (ValueError) as e:
-> 3759         construction_error(len(arrays), arrays[0].shape[1:], axes, e)
   3760 
   3761 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in construction_error(tot_items, block_shape, axes, e)
   3729         raise e
   3730     raise ValueError("Shape of passed values is {0}, indices imply {1}".format(
-> 3731         passed,implied))
   3732 
   3733 def create_block_manager_from_blocks(blocks, axes):

ValueError: Shape of passed values is (2,), indices imply (2, 12)

或者这样做

pd.DataFrame( {'data': df.Data, 'group': df.Group}, index=df.Date)

【问题讨论】:

  • 我已经编辑了我的答案 :) 有一条评论更详细地说明了实际答案。

标签: python pandas


【解决方案1】:

您可以创建一个groupby 对象,然后遍历组并进行绘图。

下面是一些代码,它获取您的数据并绘制两个“组”。还有一些额外的格式可以使图表看起来更好。

import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt

path2file = r"Example.xlsx"
_xl = pd.ExcelFile(path2file)
df = pd.read_excel(path2file, _xl.sheet_names[0], header=0) 

df.Date = df.Date.apply( lambda x: dt.datetime.strptime(x, '%Y.%m.%d').date())
df.index = df.Date # Set the Date column as your index
del df['Date'] # Remove the Date column from your data columns

grouped = df.groupby('Group') # groupby object

# Normally you would just iterate using "for k, g in grouped:" but the i
# is necessary for selecting a color.
colors = ['red', 'blue']
for i, (k, g) in enumerate(grouped):
    plt.plot_date(g['Data'].index, g['Data'], linestyle='None', marker='o', mfc=colors[i], label=k)

plt.legend()
plt.gcf().autofmt_xdate() # Format the dates with a diagonal slant to make them fit.

# Pad the data out so all markers can be seen.
pad = dt.timedelta(days=7)
plt.xlim((min(df.index)-pad, max(df.index)+pad))
plt.ylim(0,6)

【讨论】:

  • 非常感谢您。在尝试使您的答案适用于真实的 Excel 文件时,我遇到了一些问题。请查看我的问题的更新部分
  • 谢谢!多好的方法呢
  • 为什么标签(图例)有两个点?
  • 我认为这只是它们的格式化方式,表明每个数据集都是红色/蓝色的圆形标记。
  • 这似乎有点奇怪.. 但我真的很喜欢你的解决方案,因为我可以用循环做更多的分组:)
【解决方案2】:

这应该可以工作

df.pivot_table(rows=['Date'], cols=['Group'], values=['Data']).plot()

但请注意,每个数据点都是特定组中特定日期数据点的“平均值”

【讨论】:

  • @Ffisegydd 我确实喜欢他的建议(因为有些人在看这个问题可能想要这样的解决方案),但是你的回答回答了我的问题是正确的。
  • @Ffisegydd 我同意你的评论。但是,它可能仍然可以帮助那些不需要“所有”点的人。如果事实并非如此,将删除答案
  • @user1827356 如果您有更多列怎么办?您将如何选择数据列?
  • @Norfeldt 我已经更新了答案。以前的版本没有达到我的预期,至少在 0.12.0
  • @user1827356 谢谢你。我对你的答案投了赞成票,但投了反对票,所以现在只是零
猜你喜欢
  • 1970-01-01
  • 2018-11-08
  • 2020-01-14
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
相关资源
最近更新 更多