![](/img/trans.png)
[英]Converting a Pandas datetime index on a DataFrame object to *MultiIndex* with the levels “month” and “year”
[英]use only year for datetime index - pandas dataframe
我已將年份列正確轉換為日期時間索引,但是月份和日期不准確且不需要看到我的數據集僅包含年份。 我使用格式參數只設置年份,但它仍然顯示為“%Y-%M-%D”格式。
原始數據:
index song year artist genre
0 0 ego-remix 2009 beyonce knowles Pop
1 1 shes-tell-me 2009 save Rock
2 2 hello 2009 yta Pop
3 3 the rock 2009 term R&B
4 4 black-culture 2009 hughey Country
使用上面的代碼進行了更多的清理技術。
然后這里是我的數據幀代碼中的示例行:
clean_df.index = pd.to_datetime(clean_df['year'], format='%Y')
clean_df = clean_df.drop(['index', 'year'], 1)
clean_df.sort_index(inplace=True)
clean_df.head()
year song artist genre
1970-01-01 hey now caravan Rock
1970-01-01 show me abc Rock
1970-01-01 hey now xyz Pop
1970-01-01 tell me foxy R&B
1970-01-01 move up curtis R&B
是否有任何其他方法可用於將索引設置為僅年度?
你很近
clean_df.index = pd.to_datetime(clean_df['year'], format='%Y-%m-%d').year
很難提供所需的實際正確格式,因為我沒有您的原始數據,但您只需要轉換為日期對象,然后調用year
參數
我有一個類似的問題。 是這樣解決的:
df['Year'] = df.Year.astype(np.datetime64)
df['Year'] = df.Year.dt.year
df.set_index('Year')
輸出應僅顯示 4 位數字的年份。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.