将数据框子集为每个由两列组成的子样本

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

我有一个包含 N 列的大数据框。列成对出现,如下:

  • 第 1 栏:ISIN 1,每日日期顺序(债券 1 的发行至到期)
  • 第 2 栏:ISIN1 价格历史数据
  • 第 3 栏:ISIN 2,每日日期顺序(债券 2 的发行至到期)
  • 第 4 栏:ISIN2 价格历史数据 等等。

列像这样配对:前两列放在一起,然后接下来的两列,直到数据帧的末尾:

  XS0552790049  Unnamed: 5583 XS0628646480  Unnamed: 5585
0   2010-10-22          100.0   2011-05-24         99.711
1   2010-10-25          100.0   2011-05-25         99.685
2   2010-10-26          100.0   2011-05-26        100.125
3   2010-10-27          100.0   2011-05-27         99.893
4   2010-10-28          100.0   2011-05-30         99.792

我想将这个大数据框分成 N/2 个子样本,每个子样本包含一对列“ISIN 日期 + 价格”,如上所示。 我考虑过使用 for 循环,但我肯定错过了一些东西,因为它不会生成子样本。也许我索引错误。

这是我的尝试:我尝试创建一个包含每个键的子样本的字典。

sub = {}
for i in range(0,len(df.columns)+1):
    sub[i] = df.iloc[:,i:i+3]

我对 Python 还很陌生,所以欢迎提出任何建议。

python pandas dataframe subset
1个回答
0
投票

要按列对分割数据帧,假设列数为偶数:

import pandas as pd

df = pd.DataFrame(columns = ['one','two','three','four'],
                  index = range(1))
   one  two three four
0  NaN  NaN   NaN  NaN

# Use a comprehension:
dfs = [df[df.columns[2*i:2*(i+1)]] for i in range(int(len(df.columns)/2))]

这将返回成对子集的列表:

dfs
[   one  two
 0  NaN  NaN,
   three four
 0   NaN  NaN]

df[0]
   one  two
0  NaN  NaN

(不要使用

sub
作为变量名,因为这是
re
模块中的 Python 函数。)

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