【问题标题】:Python/Pandas - partitioning a pandas DataFrame in 10 disjoint, equally-sized subsetsPython/Pandas - 将 pandas DataFrame 划分为 10 个不相交、大小相等的子集
【发布时间】:2016-11-28 22:39:35
【问题描述】:
我想将 pandas DataFrame 划分为十个不相交、大小相同、随机组合的子集。
我知道我可以使用以下方法随机抽取原始 pandas DataFrame 的十分之一:
partition_1 = pandas.DataFrame.sample(frac=(1/10))
但是,我怎样才能获得其他九个分区?如果我再次执行pandas.DataFrame.sample(frac=(1/10)),则存在我的子集不是不相交的可能性。
感谢您的帮助!
【问题讨论】:
标签:
python
python-2.7
pandas
dataframe
partitioning
【解决方案1】:
从这里开始。
dfm = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo']*2,
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three']*2})
A B
0 foo one
1 bar one
2 foo two
3 bar three
4 foo two
5 bar two
6 foo one
7 foo three
8 foo one
9 bar one
10 foo two
11 bar three
12 foo two
13 bar two
14 foo one
15 foo three
Usage:
Change "4" to "10", use [i] to get the slices.
np.random.seed(32) # for reproducible results.
np.array_split(dfm.reindex(np.random.permutation(dfm.index)),4)[1]
A B
2 foo two
5 bar two
10 foo two
12 foo two
np.array_split(dfm.reindex(np.random.permutation(dfm.index)),4)[3]
A B
13 foo two
11 bar three
0 foo one
7 foo three
【解决方案2】:
假设df 是您的数据框,并且您希望N_PARTITIONS 分区大小大致相等(如果len(df) 可以被N_PARTITIONS 整除,它们的大小完全相同)。
使用np.random.permutation 置换数组np.arange(len(df))。然后使用步骤N_PARTITIONS 对该数组进行切片,并使用.iloc[] 提取数据帧的相应行。
import numpy as np
permuted_indices = np.random.permutation(len(df))
dfs = []
for i in range(N_PARTITIONS):
dfs.append(df.iloc[permuted_indices[i::N_PARTITIONS]])
由于您使用的是 Python 2.7,因此最好将 range(N_PARTITIONS) 切换为 xrange(N_PARTITIONS) 以获取迭代器而不是列表。
【解决方案3】:
使用np.random.permutations:
df.loc[np.random.permutation(df.index)]
在您可以将数据框拆分为 10 个之后,它将对数据框进行洗牌并保留列名。