pivot_table的作品,但我已經用了可讀性草書版本。
data = [['nucleus', 1790, '2012-10-01 00:00:00'],
['neuron', 364, '2012-10-02 00:00:00'],
['current', 280, '2012-10-02 00:00:00'],
['molecular', 259, '2012-10-02 00:00:00'],
['stem', 201, '2012-10-02 00:00:00']]
df = pd.DataFrame(data, columns=['q_string', 'q_visits', 'q_date'])
q_string q_visits q_date
0 nucleus 1790 2012-10-01 00:00:00
1 neuron 364 2012-10-02 00:00:00
2 current 280 2012-10-02 00:00:00
3 molecular 259 2012-10-02 00:00:00
4 stem 201 2012-10-02 00:00:00
都分配了q_string和q_date指數:
df.set_index(['q_string', 'q_date'], inplace=True)
該指數目前看起來是這樣的:
MultiIndex(levels=[['current', 'molecular', 'neuron', 'nucleus', 'stem'],
['2012-10-01 00:00:00', '2012-10-02 00:00:00']],
labels=[[3, 2, 0, 1, 4], [0, 1, 1, 1, 1]],
names=['q_string', 'q_date'])`
兩個q_string和q_date是指數的日期,我們只是取消()它將q_date放入列中。
df.unstack()
q_visits
q_date 2012-10-01 00:00:00 2012-10-02 00:00:00
q_string
current NaN 280.0
molecular NaN 259.0
neuron NaN 364.0
nucleus 1790.0 NaN
stem NaN 201.0
這絕對值得閱讀文檔。這種情況在[重塑](http://pandas.pydata.org/pandas-docs/stable/reshaping.html)部分開始時就已經涉及。 – DSM