我有一个包含 N 列的大数据框。列成对出现,如下:
列像这样配对:前两列放在一起,然后接下来的两列,直到数据帧的末尾:
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 还很陌生,所以欢迎提出任何建议。
要按列对分割数据帧,假设列数为偶数:
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 函数。)