[英]Always got NaN when converting dictionary to multiindex pandas DataFrame if the index including datetime.date object
[英]Converting a Pandas datetime index on a DataFrame object to *MultiIndex* with the levels “month” and “year”
假設我有一個包含每月 datetime
索引的數據表(以下代碼給出了從一月到十二月的兩年):
import pandas as pd
import numpy as np
from datetime import datetime
N = 12*2
c = [datetime(1970 + i//12, (i%12)+1, 1) for i in range(N)]
d = pd.DataFrame(np.random.rand(N), index=c)
print(d)
將DateTimeIndex
轉換為具有單獨的 month
和year
級別的MultiIndex
的最佳方法是什么? 也許有一種方法可以使用groupby
來做到這一點,但是我不確定。
您可以根據year
和month
構造一個MultiIndex
對象,並將其分配給數據框的索引:
import pandas as pd
d.index = pd.MultiIndex.from_arrays([d.index.year, d.index.month])
d.index
# MultiIndex(levels=[[1970, 1971], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
# labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])
d.head()
# 0
#1970 1 0.657130
# 2 0.047241
# 3 0.984799
# 4 0.868508
# 5 0.678536
d.index = pd.MultiIndex.from_tuples(d.reset_index()['index'].\
apply(lambda x:(x.year,x.month)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.