下面是一个示例代码,用于保持两个时间序列的常见观察:
import pandas as pd
# 创建示例时间序列数据
data1 = {'Date': ['2021-01-01', '2021-01-02', '2021-01-03'],
'Value1': [10, 20, 30]}
data2 = {'Date': ['2021-01-01', '2021-01-03', '2021-01-04'],
'Value2': [100, 200, 300]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
# 将日期列转换为日期时间类型
df1['Date'] = pd.to_datetime(df1['Date'])
df2['Date'] = pd.to_datetime(df2['Date'])
# 将日期列设置为索引
df1.set_index('Date', inplace=True)
df2.set_index('Date', inplace=True)
# 使用merge函数合并两个时间序列
merged_df = pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
# 打印合并后的时间序列
print(merged_df)
输出结果为:
Value1 Value2
Date
2021-01-01 10.0 100.0
2021-01-02 20.0 NaN
2021-01-03 30.0 200.0
2021-01-04 NaN 300.0
上述代码首先创建了两个示例的时间序列数据,然后使用pd.to_datetime
函数将日期列转换为日期时间类型。接下来,使用set_index
函数将日期列设置为索引。最后,使用pd.merge
函数将两个时间序列合并在一起,通过指定left_index=True
和right_index=True
来基于索引进行合并,并通过how='outer'
参数保持两个时间序列的常见观察。最后,打印合并后的时间序列数据。
上一篇:保持两个热力图之间的选择同步
下一篇:保持两个遥控器同步