如何将数据帧从长转换为宽,值在索引中按年份分组?

Xav*_*zet 6 python arrays matplotlib dataframe pandas

下面的代码与我以前使用的 csv 一起使用,两个 csv 的列数相同,并且列的名称相同。

这里工作的 csv 的数据

此处没有的 csv 数据

这个错误是什么意思?为什么我收到这个错误?

from pandas import read_csv
from pandas import DataFrame
from pandas import Grouper
from matplotlib import pyplot

series = read_csv('carringtonairtemp.csv', header=0, index_col=0, parse_dates=True, squeeze=True)

groups = series.groupby(Grouper(freq='A'))
years = DataFrame()

for name, group in groups:
    years[name.year] = group.values

years = years.T

pyplot.matshow(years, interpolation=None, aspect='auto')
pyplot.show()
Run Code Online (Sandbox Code Playgroud)

错误

from pandas import read_csv
from pandas import DataFrame
from pandas import Grouper
from matplotlib import pyplot

series = read_csv('carringtonairtemp.csv', header=0, index_col=0, parse_dates=True, squeeze=True)

groups = series.groupby(Grouper(freq='A'))
years = DataFrame()

for name, group in groups:
    years[name.year] = group.values

years = years.T

pyplot.matshow(years, interpolation=None, aspect='auto')
pyplot.show()
Run Code Online (Sandbox Code Playgroud)

Tre*_*ney 3

  • 以所示方式迭代创建数据帧的问题是,它需要新列来匹配现有数据帧索引的长度year
  • 在较小的数据集中,所有年份都是 365 天,没有缺失的日子。
  • 较大的数据集具有 365 天和 366 天的混合长度年份,并且缺少 1990 年和 2020 年的数据,这导致ValueError: Length of values (365) does not match length of index (252).
  • 以下是一个更简洁的脚本,它实现了所需的数据框形状和绘图。
    • 此实现不存在数据长度不等的问题。
import pandas as pd
import matplotlib.pyplot as plt

# links to data
url1 = 'https://raw.githubusercontent.com/trenton3983/stack_overflow/master/data/so_data/2020-09-19%20%2063975678/daily-min-temperatures.csv'
url2 = 'https://raw.githubusercontent.com/trenton3983/stack_overflow/master/data/so_data/2020-09-19%20%2063975678/carringtonairtemp.csv'

# load the data into a DataFrame, not a Series
# parse the dates, and set them as the index
df1 = pd.read_csv(url1, parse_dates=['Date'], index_col=['Date'])
df2 = pd.read_csv(url2, parse_dates=['Date'], index_col=['Date'])

# groupby year and aggregate Temp into a list
dfg1 = df1.groupby(df1.index.year).agg({'Temp': list})
dfg2 = df2.groupby(df2.index.year).agg({'Temp': list})

# create a wide format dataframe with all the temp data expanded
df1_wide = pd.DataFrame(dfg1.Temp.tolist(), index=dfg1.index)
df2_wide = pd.DataFrame(dfg2.Temp.tolist(), index=dfg2.index)

# plot
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 10))

ax1.matshow(df1_wide, interpolation=None, aspect='auto')
ax2.matshow(df2_wide, interpolation=None, aspect='auto')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述