我正在寻找有关如何平滑趋势线的建议。
这是代码:
import pandas as pd
from numpy import random
#Generating the data frame
df = pd.DataFrame(data = random.randn(5,4), index = ['A','B','C','D','E'],
columns = ['W','X','Y','Z'])
df['W'] = ['10/01/2018 12:00:00','10/03/2018 13:00:00',
'10/03/2018 12:30:00','10/04/2018 12:05:00',
'10/08/2018 12:00:15']
pd.to_datetime(df['W'])
print(df.head())
#Plotting hte graph
fig, ax = plt.subplots()
df.plot(x="W", y="X", ax=ax, color='salmon', alpha=0.5, marker='o')
df.plot(x="W", y="Y", ax=ax, color='royalblue', alpha=0.4, marker='o')
这就是我得到的:
答案 0 :(得分:1)
您可以使用df.resample
方法和df.interpolate
来完成您想要的事情。
首先,df.resample
计算我们将进行插值的日期时间。之后,我们可以进行插值。
import pandas as pd
from numpy import random
import matplotlib.pyplot as plt
#Generating the data frame
df = pd.DataFrame(data = random.randn(5,4), index = ['A','B','C','D','E'],
columns = ['W','X','Y','Z'])
df['W'] = pd.to_datetime(['10/01/2018 12:00:00','10/03/2018 13:00:00',
'10/03/2018 12:30:00','10/04/2018 12:05:00',
'10/08/2018 12:00:15'], infer_datetime_format=True)
#Plotting
fig, ax = plt.subplots(1, 1)
df.plot(x="W", y="X", ax=ax, color='salmon', alpha=0.5, marker='o')
df.plot(x="W", y="Y", ax=ax, color='royalblue', alpha=0.4, marker='o')
df = df.resample('T', on='W').mean()
df.interpolate(method='spline', order=3, inplace=True)
df.plot(y='X', alpha=0.5, ax=ax, legend=False)
df.plot(y='Y', alpha=0.4, ax=ax, legend=False)