3

是否可以读取这种格式的 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 )中看不到任何内容

4

1 回答 1

14

阅读 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
于 2013-10-04T14:23:44.500 回答