python - Pandas 将时间列添加到日期索引

标签 python pandas multiple-columns reshape timedelta

我有一个数据框,日期索引类型是时间戳,时间列是datetime.Time:

            Time  Value
Date
2004-05-01  0:15  3.58507  
2004-05-02  0:30  3.84625
              ...

如何将其转换为:

                    Value
Date
2004-05-01 0:15     3.74618
2004-05-01 0:30     3.58507
2004-05-01 0:45     3.30998

我写了一个可以工作的代码,但它不是很 pythonic:

ind = frame.index.get_level_values(0).tolist()
tms = frame['Time']
new_ind = []
for i in range(0, len(ind)):
    tm = tms[i]
    val = ind[i] + timedelta(hours=tm.hour, minutes=tm.minute, seconds=tm.second)
    new_ind.append(val)

frame.index = new_ind
del frame['Time']

最佳答案

您可以先转换列 Time to_timedelta , 然后添加到 index, dropTime 并在必要时设置索引 name:

df.Time = pd.to_timedelta(df.Time + ':00', unit='h')
df.index = df.index + df.Time
df = df.drop('Time', axis=1)
df.index.name = 'Date'
print (df)
                       Value
Date                        
2004-05-01 00:15:00  3.58507
2004-05-02 00:30:00  3.84625

如果 Time 列对我来说是 datetime.time 首先转换为 string(如有必要,添加 :00):

df.Time = pd.to_timedelta(df.Time.astype(str), unit='h')
df.index = df.index + df.Time
df = df.drop('Time', axis=1)
df.index.name = 'Date'
print (df)
                       Value
Date                        
2004-05-01 00:15:00  3.58507
2004-05-02 00:30:00  3.84625

关于python - Pandas 将时间列添加到日期索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41530413/

相关文章:

python-2.7 - 使用 .isin() 检查 nan 的 Pandas 无法正常工作

html - 在移动 View 中重新排列列顺序

excel - 使用 PowerShell 将一个 csv 文件中的列复制到另一个文件

c++ - 完美柱方程 C++

python - 如何从 Python 访问 DirectSound 设备信息?

python-3.x - 值错误 : could not convert string to float: '"152. 7"'

python - 识别缺失值并返回包含这些值的列表

python - 如何在 Python 中打印具有不同数据类型的嵌套列表的元素?

python - 在 scikit-learn 中实现 K 邻居分类器,每个对象具有 3 个特征

javascript - python: 无法打开文件 'scriptbootstrap.py'