简体   繁体   English

仅使用年份作为日期时间索引 - 熊猫数据框

[英]use only year for datetime index - pandas dataframe

I've properly converted my year column into a datetime index, however the month and date are inaccurate and unneeded seeing my dataset only includes year.我已将年份列正确转换为日期时间索引,但是月份和日期不准确且不需要看到我的数据集仅包含年份。 I've used the format parameter to set year only, however it's still showing as "%Y-%M-%D" format.我使用格式参数只设置年份,但它仍然显示为“%Y-%M-%D”格式。

Original data:原始数据:

    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

conducted a few more scrubbing techniques with the above code.使用上面的代码进行了更多的清理技术。

Then here are example rows from my dataframe code:然后这里是我的数据帧代码中的示例行:

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

Is there any other method to be used to set index as annual only?是否有任何其他方法可用于将索引设置为仅年度?

You were close你很近

clean_df.index = pd.to_datetime(clean_df['year'], format='%Y-%m-%d').year

It's hard to provide the actual correct format needed because I don't have your original data, but you just need to transform to date object and then call the year parameter很难提供所需的实际正确格式,因为我没有您的原始数据,但您只需要转换为日期对象,然后调用year参数

I had a similar issue.我有一个类似的问题。 Solved it this way:是这样解决的:

    df['Year'] = df.Year.astype(np.datetime64)
    df['Year'] = df.Year.dt.year
    df.set_index('Year')

Output should only show the year with 4 digits.输出应仅显示 4 位数字的年份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM