如何将 pandas 中季度数据的字符串列转换为我可以绘制的东西

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

我有一个看起来像这样的数据框:

哎呀:

    Quarter         London      UK          NaN
6   Mar-May 1992    0.12305     0.098332    NaN
7   Apr-Jun 1992    0.123895    0.097854    NaN
8   May-Jul 1992    0.124076    0.098878    NaN
9   Jun-Aug 1992    0.127796    0.099365    NaN
10  Jul-Sep 1992    0.126064    0.099371    NaN

我尝试在季度中使用 PeriodIndex,以便绘制数据,但它一直给我错误。接下来我可以尝试什么?

我尝试使用的代码:

quarter_column = df.Quarter
# create PeriodIndex
periods = pd.PeriodIndex(quarter_column, freq='Q-Mar')
pd.DataFrame(df, index=periods)

错误是:

DateParseError: Unknown datetime string format, unable to parse: MAR-MAY 1992
python pandas
1个回答
1
投票

显然

PeriodIndex
不接受该格式字符串。您的宿舍也重叠,这使得定义
PeriodIndex
.

具有挑战性

但是,你需要把它转换成

PeriodIndex
吗?如果您的数据已经按顺序排序和索引(6、7、8、9 ...),您可以使用以下代码:

# Plot the data against the dataframe's index.
# For example, the London series is actually plotted as:
# (6, 0.12305), (7, 0.123895), (8, 0.124076), ...
ax = df[["London", "UK"]].plot(marker="o")
# Tick the x-axis the same as the index, i.e: 6, 7, 8..., not 6, 6.5, 7, 7.5...
ax.xaxis.set_ticks(df.index)
# Label the ticks
ax.xaxis.set_ticklabels(df["Quarter"])

结果:

© www.soinside.com 2019 - 2024. All rights reserved.