日期时间索引仅使用年份 - pandas 数据框
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 位数字的年份。
我已将我的年份列正确转换为日期时间索引,但是月份和日期不准确且不需要,因为我的数据集仅包含年份。我使用格式参数仅设置年份,但它仍然显示为“%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 位数字的年份。