我有一个索引数据,它有77000行。
我想将每7000行分组成一个更高维的多索引,生成11个高维索引组。
我知道我可以通过所有的索引编写一个循环,创建一个元组并通过dataframe.MultiIndex.from_tuples方法分配它。
有一种优雅的方法来做这件简单的事情吗?
发布于 2015-07-31 15:03:01
您可以使用 function创建一个可以添加到索引中的新列。
下面是一个创建五个组/块的示例:
df = pd.DataFrame({'data':range(1,10)})
df['chunk'] = pd.qcut(df.data, 5, labels=range(1,6))
df.set_index('chunk', append=True, inplace=True)
df
data
index chunk
0 1 1
1 1 2
2 2 3
3 2 4
4 3 5
5 4 6
6 4 7
7 5 8
8 5 9您可以执行df['chunk'] = pd.qcut(df.index, 11)来将块分配给数据帧。
发布于 2015-07-31 15:58:59
下面的代码在0-10范围内创建一个有序列,该列被平铺到您的DataFrame长度。由于您希望根据旧索引和新折叠进行分组,因此在执行groupby之前,首先需要重置索引。
groups = 11
folds = range(groups) * (len(df) // groups + 1)
df['folds'] = folds[:len(df)]
gb = df.reset_index().groupby(['old_index', 'folds'])其中old_index显然是索引的名称。
如果您希望有顺序组(例如,前7k行、下7k行等),则可以执行以下操作:
df['fold'] = [i // (len(df) // groups) for i in range(len(df))]注意://操作符用于地板分割,以截断任何余数。
发布于 2015-07-31 18:20:42
另一种方法是使用整数除法//,假设数据帧具有默认的整数索引:
import pandas as pd
import numpy as np
# data
# ===============================================
df = pd.DataFrame(np.random.randn(10), columns=['col'])
df
# processing
# ===============================================
df['chunk'] = df.index // 5
df.set_index('chunk', append=True)
col
chunk
0 0 2.0955
1 0 -1.2891
2 0 -0.3313
3 0 0.1508
4 0 -1.0215
5 1 0.6051
6 1 -0.3227
7 1 -0.6394
8 1 -0.7355
9 1 0.5949 https://stackoverflow.com/questions/31749090
复制相似问题