【问题标题】:How to put results of loop into a list?如何将循环结果放入列表中?
【发布时间】:2016-12-09 07:41:40
【问题描述】:

我有一个数据集:

   a        b      c
11/01/1999  8   367235
11/01/1999  5   419895
11/01/1999  1   992194
23/03/1999  4   419895
30/04/1999  1   992194
02/06/1999  9   419895
08/08/1999  2   367235
12/08/1999  3   419895
17/08/1999  10  992194
22/10/1999  3   419895
04/12/1999  4   992194
04/03/2000  2   367235
29/09/2000  9   367235
30/09/2000  9   367235

我正在尝试制作一个可视化,显示随时间变化的值集(“b”列)(“a”列):

*请注意,这只是为了描绘我的目标 - 它不是我的数据集。

我将数据集更改为数据透视表,其中列出了第一列中的“c”列值、顶行中的“a”值以及数据框中的“b”值。令人高兴的是,我已经能够从数据透视表中提取值行,并将其用作 matplotlib 图的输入(表示图表上的 y 值)。不幸的是,我无法以可接受的格式提取数据透视表的标题,这是一个问题,因为标题代表我图表上的 x 值。

这是有效的代码部分:

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from datetime import datetime

df = (pd.read_csv('orcs.csv'))
df_wanted = pd.pivot_table(
    df,
    index='c',
    columns='a',
    values='b')
lala = df_wanted.as_matrix()
x=np.array(lala[1,:])
y = (df_wanted.columns.astype(str).tolist())

这是代码中不起作用的部分。

我尝试了几种替代方法(包括错误消息):

1.

plt.plot(x,y)# error: could not convert string to float: '02/06/1999'

2.

for i in range(len(y)):
    c= (y[i])
    print(c) #no error message, but gives me an output I don't know how to capture for the plt.plot input.

3.

for i in range(len(y)):
    c= (y[i])
    f = datetime.strptime(c, '%d/%m/%Y')
    v=list(f)
    plot.plot(x,v) # error message:'datetime.datetime' object is not iterable

任何帮助表示赞赏

【问题讨论】:

    标签: python datetime matplotlib pivot


    【解决方案1】:

    您必须交换indexcolumns,然后将index 转换为datetime。然后只需.plot()

    df_wanted = pd.pivot_table(df, columns='c',
                               index='a', values='b')    
    df_wanted.index = pd.to_datetime(df_wanted.index)
    df_wanted.plot()
    

    【讨论】:

    • llya V. Schurov,非常非常感谢您提供如此优雅的解决方案。您还让我不必编写代码来处理我的 40,000 个 y 值行。我一直在尝试这样做一段时间,所以我很放心它的工作原理。非常感谢。
    【解决方案2】:

    如果您想使用matplotlib.pyplot 进行绘图,那么您只能指定数字坐标(即非字符串)。但是您可以将str 标签分配给这些坐标

    所以你可能要考虑这种代码:

    from matplotlib import pyplot as plt
    import datetime
    
    yValues = [10,15,8,7,1]
    xLabels = ['a', datetime.datetime.now().strftime("%Y-%M-%d"), 
                        'b', 'c', 'd']
    
    fig = plt.figure()     
    ax = fig.add_axes([0.1, 0.2, 0.8, 0.7])
    ax.plot(yValues)
    ax.set_xticks(range(len(yValues)))
    ax.set_xticklabels(xLabels, rotation = 'vertical')
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2018-12-27
      • 2019-09-21
      相关资源
      最近更新 更多