所以现在我有3列索引值 . 当我 reset_index 时,我'm going to have 3 columns pushed onto the front of the dataframe. So, I' ll reset_index并使用 .reset_index().iloc[:, :3] 获取前三列并将其传递给 pd.to_datetime
lol = [[y, m, d] for y, d in zip(df.index, df.day) for m in df.columns[1:]]
columns = ['year', 'month', 'day']
d1 = pd.DataFrame(lol, columns=columns)
dates = pd.to_datetime(d1, errors='coerce')
m = dates.notnull().values
pd.Series(df.drop('day', 1).values.ravel()[m], dates[m])
1 回答
我们希望利用
pd.to_datetime
功能,该功能将数据帧与相关命名的列相关联 . 在这种情况下'year'
,'month'
和'day'
.因此,下面的解决方案旨在使用这三列创建这样的数据帧并将其传递给
pd.to_datetime
.我们已经在索引中有
'year'
...所以让's get everything in the index. Let'开始在df.set_index('day', append=True)
索引中获取'day'
接下来,我们将
'month'
纳入索引 . 但是现在它在列中 . 首先,我们用.rename_axis('month', 1)
重命名列然后我们把它放在
.stack()
的索引中所以现在我有3列索引值 . 当我
reset_index
时,我'm going to have 3 columns pushed onto the front of the dataframe. So, I' ll reset_index并使用.reset_index().iloc[:, :3]
获取前三列并将其传递给pd.to_datetime
由于某些组合可能不存在,例如
'1964-02-31'
,我们传递errors='coerce'
,这将返回NaT
这样的日期 .最后,我们使用
loc
过滤结果并从索引中删除空值 .样本数据
Solution
完整数据
Alternative