【问题标题】:Pandas: Read a CSV of timeseries data with 'column' header as row elementPandas:以“列”标题作为行元素读取时间序列数据的 CSV
【发布时间】:2013-10-11 13:47:38
【问题描述】:

是否可以读取这种格式的 CSV 文件:

2013-01-01,A,1
2013-01-02,A,2
2013-01-03,A,3
2013-01-04,A,4
2013-01-05,A,5
2013-01-01,B,1
2013-01-02,B,2
2013-01-03,B,3
2013-01-04,B,4
2013-01-05,B,5

进入一个像这样结束的DataFrame:

             A   B
2013-01-01   1   1
2013-01-02   2   2
2013-01-03   3   3
2013-01-04   4   4
2013-01-05   5   5

我在 I/O 文档中看不到任何内容 (http://pandas.pydata.org/pandas-docs/dev/io.html)

【问题讨论】:

    标签: python csv pandas time-series


    【解决方案1】:

    您在 DataFrame 中阅读后,为什么不重塑(枢轴)?

    In [1]: df = pd.read_csv('foo.csv', sep=',', parse_dates=[0], header=None,
                             names=['Date', 'letter', 'value'])
    
    In [2]: df
    Out[2]: 
                     Date letter  value
    0 2013-01-01 00:00:00      A      1
    1 2013-01-02 00:00:00      A      2
    2 2013-01-03 00:00:00      A      3
    3 2013-01-04 00:00:00      A      4
    4 2013-01-05 00:00:00      A      5
    5 2013-01-01 00:00:00      B      1
    6 2013-01-02 00:00:00      B      2
    7 2013-01-03 00:00:00      B      3
    8 2013-01-04 00:00:00      B      4
    9 2013-01-05 00:00:00      B      5
    
    In [3]: df.pivot(index='Date', columns='letter', values='value')
    Out[3]:
    letter      A  B
    Date            
    2013-01-01  1  1
    2013-01-02  2  2
    2013-01-03  3  3
    2013-01-04  4  4
    2013-01-05  5  5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2013-03-11
      • 2019-06-17
      • 2018-09-13
      相关资源
      最近更新 更多