将数据框列名从字符串格式更改为日期时间 [英] Change dataframe column names from string format to datetime
本文介绍了将数据框列名从字符串格式更改为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,其中列的名称是字符串形式的日期(年月)。如何将这些名称转换为日期时间格式?
我尝试这样做:
I have a dataframe where the names of the columns are dates (Year-month) in the form of strings. How can I convert these names in datetime format? I tried doing this:
new_cols = pd.to_datetime(df.columns)
df = df[new_cols]
但是我得到了错误:
KeyError: "DatetimeIndex(
['2000-01-01', '2000-02-01',
'2000-03-01', '2000-04-01',
'2000-05-01', '2000-06-01',
'2000-07-01', '2000-08-01',
'2000-09-01', '2000-10-01',
'2015-11-01', '2015-12-01',
'2016-01-01', '2016-02-01',
'2016-03-01', '2016-04-01',
'2016-05-01', '2016-06-01',
'2016-07-01', '2016-08-01'],
dtype='datetime64[ns]', length=200, freq=None) not in index"
谢谢!
推荐答案
如果按 loc
列选择的值未更改,则获取 KeyError
。
If select by loc
columns values was not changed, so get KeyError
.
因此您需要将输出分配给列
:
So you need assign output to columns
:
df.columns = pd.to_datetime(df.columns)
样本:
cols = ['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01', '2000-05-01']
vals = np.arange(5)
df = pd.DataFrame(columns = cols, data=[vals])
print (df)
2000-01-01 2000-02-01 2000-03-01 2000-04-01 2000-05-01
0 0 1 2 3 4
print (df.columns)
Index(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01', '2000-05-01'], dtype='object')
df.columns = pd.to_datetime(df.columns)
print (df.columns)
DatetimeIndex(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01',
'2000-05-01'],
dtype='datetime64[ns]', freq=None)
也可以转换为期间:
print (df.columns)
Index(['2000-01-01', '2000-02-01', '2000-03-01', '2000-04-01', '2000-05-01'], dtype='object')
df.columns = pd.to_datetime(df.columns).to_period('M')
print (df.columns)
PeriodIndex(['2000-01', '2000-02', '2000-03', '2000-04', '2000-05'],
dtype='period[M]', freq='M')
这篇关于将数据框列名从字符串格式更改为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文