python - 从隐藏在多索引中的年份和月份创建日期时间

标签 python datetime pandas multi-index datetimeindex

我有一个数据框,其中年份和月份隐藏在多索引中。我想创建一个日期时间索引作为附加列(或具有相同索引的单独系列)。

                                           price            
                                            mean     mom_2  
foo          bar              year month                                      
997182819645 11               2010 1      1.1900  3.000000  
                                   2      2.2625  4.001769  

我考虑将两个级别的索引作为字符串添加在一起,然后将该序列读入pd.to_datetime()。然而,添加两个索引时,我遇到了问题。我可以将它们添加为整数就好,但是如果我想将它们添加为字符串,我会遇到一些错误:

In[193]: df.index.get_level_values('year').values.astype(str)
Out[193]: 

array(['2010', '2010', '2010', ..., '2014', '2014', '2014'], 
      dtype='<U21')
In[194]: df.index.get_level_values('month').values.astype(str)
Out[194]: 

array(['1', '2', '3', ..., '10', '11', '12'], 
      dtype='<U21')
In[195]: df.index.get_level_values('month').values.astype(str) + df.index.get_level_values('year').values.astype(str)

TypeError: ufunc 'add' did not contain a loop with signature matching types
 dtype('<U21') dtype('<U21') dtype('<U21')

如何在此处添加创建日期时间索引?

最佳答案

我认为你可以使用to_datetime ,但首先需要多个 yearmonth 值:

y = df.index.get_level_values('year')
m = df.index.get_level_values('month')

df['Date'] = pd.to_datetime(y * 10000 + m * 100 + 1, format="%Y%m%d")
print (df)
                              price                 Date
                                foo       bar           
foo          bar year month                             
997182819645 11  2010 1      1.1900  3.000000 2010-01-01
                      2      2.2625  4.001769 2010-02-01

如果需要,请将列附加到索引:

df['Date'] = pd.to_datetime(y * 10000 + m * 100 + 1, format="%Y%m%d")
df.set_index('Date', append=True, inplace=True)
print (df)
                                         price          
                                           foo       bar
foo          bar year month Date                        
997182819645 11  2010 1     2010-01-01  1.1900  3.000000
                      2     2010-02-01  2.2625  4.001769

另一种解决方案,创建新的DataFrame,但需要最后0.18.1 version :

y = df.index.get_level_values('year')
m = df.index.get_level_values('month')
d = pd.Index(len(df.index) * [1], name='day')
df1 = pd.DataFrame({'year':y, 'month':m, 'day':d}, index=df.index)

df['Date']  = pd.to_datetime(df1)
print (df)
                              price                 Date
                                foo       bar           
foo          bar year month                             
997182819645 11  2010 1      1.1900  3.000000 2010-01-01
                      2      2.2625  4.001769 2010-02-01

关于python - 从隐藏在多索引中的年份和月份创建日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39412123/

相关文章:

python - 具有按相邻列值进行多索引的 DataFrame 切片

python - 如何使用 python 提取 exe-archive 的内容?

python plot 和 powerlaw 适合

c# - 从日期时间字段获取日期 Mysql 查询

c# - DateTime.TryParseExact C# 有效格式和解析

python - 在函数中编辑数据帧 'inplace',或返回编辑后的数据帧?

python - DecimalField 将零转换为 0E-10

python - 快速替换字符串中的字符并检查子字符串是否是回文

java - 如何转义 JSON 字符串中日期时间值内的冒号

python - 如何对数据帧的列中的元组进行排序