[英]Converting a Pandas datetime index on a DataFrame object to *MultiIndex* with the levels “month” and “year”
[英]Always got NaN when converting dictionary to multiindex pandas DataFrame if the index including datetime.date object
在以下示例中,當日期 object 在索引中時,pandas 無法正確生成 DataFrame。 它顯示的不是 6,而是 NaN。
import pandas as pd
import datetime
X = {(datetime.date(2020, 6, 3), 'A'): {'B': 6}}
df = pd.DataFrame.from_dict(X, orient='index')
print(df)
B
2020-06-03 A NaN
沒有 datetime.date 作為索引它工作正常。
X = {('OK', 'A'): {'B': 6}}
df = pd.DataFrame.from_dict(X, orient='index')
print(df)
B
OK A 6
這里有什么問題? 我正在使用 python 3.8.3 和 pandas 1.0.4
有趣的是,單個datetime
索引可以正常工作,具有任何其他類型(包括另一個datetime
)的復合datetime
索引確實給出NaN
。 我發現的唯一解決方法是使用pandas
本機datetime
時間:
import pandas as pd
X = {(pd.datetime(2020, 6, 3), 'A'): {'B': 6}}
df = pd.DataFrame.from_dict(X, orient='index')
print(df)
產生
FutureWarning: The pandas.datetime class is deprecated and will be removed from pandas in a future version. Import from datetime module instead.
X = {(pd.datetime(2020, 6, 3), 'A'): {'B': 6}}
B
2020-06-03 A 6
然而,警告表明這不是一個面向未來的解決方案,您的原始表格將是唯一的選擇(目前是錯誤的)。 我有 Python 3.7.6 和 pandas 1.0.3。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.