【问题标题】:How to merge 5 columns of a dataframe into one long column of new dataframe?如何将数据框的 5 列合并为一长列新数据框?
【发布时间】:2021-12-26 21:05:23
【问题描述】:

我有一个数据框BaseResult,其中包含 41 年的每日温度数据(41 行 x 365 列),其中行代表年,列代表天。我想以每天为中心的每 5 列合并成一个长列,这样我就有了一个新的数据框,RollingPercentile,即(200 行 x 365 列)。这里 Jan 03 的列将包含 Jan 01-05 的数据,Jan 04 的列将包含 Jan 02-06 的数据等。到目前为止,我只能水平合并列,即一列中的 3 个值一列更长,数据是 3 倍。

source_col_loc=BaseResult.columns.get_loc('01-01')
BaseResult['01-01']=BaseResult.iloc[:,source_col_loc+1:source_col_loc+4].apply(
    lambda x: ",".join(x.astype(str)),axis=1)

我怎样才能做到这一点,以便它们垂直合并,以便我可以遍历整个数据框?我的最终目标是计算每列的第 90 个百分位数,其中包含以 Percentile90=RollingPercentile.percentile(0.9) 索引的日期为中心的 5 天数据,这样我最终得到一个包含 365 个值的数组。

【问题讨论】:

  • 当我尝试解决您的问题时:这是生成类似于您的数据框的代码。如果你编辑你的问题,会更容易回答。 day = [i for i in range(366)] df = pd.DataFrame(np.random.randint(0,42,size=(42, 366)), columns=list(day))

标签: python pandas dataframe numpy weather


【解决方案1】:

使用窗口进行计算

滚动百分位数聚合多行数据以获得一个值。

df.rolling(window=window, min_periods=min_periods).quantile(perc)

df.rolling(window=window, min_periods=min_periods).mean()

df.rolling(window=window, min_periods=min_periods).std()

df1.rolling(window=window, min_periods=min_periods).apply(lambda x: 
stats.linregress(x, df2), raw=False)

这些是您可以应用的一些窗口和滚动聚合类型

【讨论】:

  • 我需要对行和列进行聚合。是否可以使用这些来做到这一点?
猜你喜欢
  • 2021-07-21
  • 2023-01-23
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2017-08-02
相关资源
最近更新 更多