如何从 pandas 折线图中删除空日期

问题描述 投票:0回答:1

我使用 pandasmatplotlib 绘制了线图。我有时间序列数据,中间遗漏了一些日期(这不是必需的)。

日期

"2024-01-01"
"2024-01-02"
"2024-01-03"
"2024-01-04"
"2024-01-05"
"2024-01-08"
"2024-01-09"
"2024-01-10"
"2024-01-11"
"2024-01-12"
"2024-01-15"
"2024-01-16"
"2024-01-17"
"2024-01-18"
"2024-01-19"
"2024-01-20"

代码

dataframe = pd.DataFrame(databaseData,columns=['ticker','tdate','ttime','open','high','low','close','volume','openinterest'])
dataframe['tdate'] = pd.to_datetime(dataframe['tdate'].astype(str) + ' ' + dataframe['ttime'])
dataframe['sma'] = pd.Series(dataframe['close']).rolling(window=3).mean()
dataframe = dataframe.dropna(subset=['close'])
print(dataframe)
dataframe['close'] = pd.to_numeric(dataframe['close'])
dataframe.plot.line(x='tdate',y='close')
plot.show()

Graph

在图表中,如何删除不需要的日期并平滑图表。

我尝试在情节中添加

x_compat=True
,但仍然没有运气

python pandas matplotlib
1个回答
0
投票

您可以对时间序列重新采样,以确保包含所有日期,然后根据需要删除或前向填充缺失值。

import pandas as pd
import matplotlib.pyplot as plt

# Create dataframe and combine date and time columns
dataframe['tdate'] = pd.to_datetime(dataframe['tdate'].astype(str) + ' ' + dataframe['ttime'])
dataframe.set_index('tdate', inplace=True)

# Calculate rolling mean
dataframe['sma'] = dataframe['close'].rolling(window=3).mean()

# Drop rows with missing 'close' and resample to daily frequency
dataframe = dataframe.dropna(subset=['close'])
dataframe_resampled = dataframe.resample('D').last().dropna(subset=['close'])

# Plot the data
dataframe_resampled.plot.line(y='close')
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.