【问题标题】:plot pandas data frame but most columns have zeros绘制熊猫数据框,但大多数列都有零
【发布时间】:2013-11-07 00:53:30
【问题描述】:

我是 pandas 和 ipython 的新手,我只是设置了所有东西,目前正在玩。我有以下数据框:

  Field  10   20   30   40   50   60   70   80   90   95
0   A   0    0    0    0    0    0    0    0    1    3
1   B   0    0    0    0    0    0    0    1    4   14
2   C   0    0    0    0    0    0    0    1    2    7
3   D   0    0    0    0    0    0    0    1    5   15
4   u   0    0    0    0    0    0    0    1    5   14
5   K   0    0    0    0    0    0    1    2    7   21
6   S   0    0    0    0    0    0    0    1    3    8
7   E   0    0    0    0    0    0    0    1    3    8
8   F   0    0    0    0    0    0    0    1    6   16

我使用了一个 csv 文件来导入这些数据:

df = pd.read_csv('/mycsvfile.csv', 
                         index_col=False, header=0)

如您所见,列的帖子为零,此数据框有大量行,但有可能在列中大多数行可能为零,而剩余一两行的值类似于“70”。

我很想知道我怎样才能得到这个漂亮的图表,我可以在其中显示 70、80、95 列的重点。

我找到了以下教程:[http://pandas.pydata.org/pandas-docs/version/0.9.1/visualization.html][1] 但我仍然无法得到一个好身材。

【问题讨论】:

    标签: matplotlib pandas ipython


    【解决方案1】:

    这在一定程度上取决于您希望如何处理零值,但这里有一种方法:

    df = pd.DataFrame({'a': [0,0,0,0,70,0,0,90,0,0,80,0,0],
                           'b': [0,0,0,50,0,60,0,90,0,80,0,0,0]})
    
    fig, axs = plt.subplots(1,2,figsize=(10,4))
    
    # plot the original, for comparison
    df.plot(ax=axs[0])
    
    for name, col in df.iteritems():
        col[col != 0].plot(ax=axs[1], label=name)
    
    axs[1].set_xlim(df.index[0],df.index[-1])
    axs[1].set_ylim(bottom=0)
    axs[1].legend(loc=0)
    

    您也可以使用.replace(0,np.nan),但如果中间有 nan,matplotlib 不会画线。因此,您可能最终还是会遍历列(例如,然后使用 dropna().plot())。

    【讨论】:

    • 谢谢,您认为直方图可行吗? X 轴为字段,y 为 10、20 ....?我该如何做一个历史记录?
    猜你喜欢
    • 2017-06-09
    • 2020-07-28
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2017-10-10
    • 2020-01-14
    • 2017-05-28
    • 2015-02-04
    相关资源
    最近更新 更多