Python 2.7 随机采样数据帧的行,直到达到所需的列和
我有这样一个数据帧:Python 2.7 随机采样数据帧的行,直到达到所需的列和,python-2.7,pandas,Python 2.7,Pandas,我有这样一个数据帧: ID key acres 1 156 10 2 157 60 3 158 50 4 159 1 5 160 9 6 161 110 我想随机选择行,直到从每个采样行中选择的acres总和达到150,或者尽可能接近150。我想存储所有选定行的“ID” 我目前正在尝试这样做: acres = 0 obid = [] while acres <= 150: rows = random.sample(df.in
ID key acres
1 156 10
2 157 60
3 158 50
4 159 1
5 160 9
6 161 110
我想随机选择行,直到从每个采样行中选择的acres
总和达到150,或者尽可能接近150。我想存储所有选定行的“ID”
我目前正在尝试这样做:
acres = 0
obid = []
while acres <= 150:
rows = random.sample(df.index, 1)
sample= df.ix[rows]
acres = acres + sample['acres']
obid.append(sample['ID'])
df= df.drop(rows)
这让我相信有一种更好的方法。让我们试试这样的方法:
ID key acres
1 156 10
2 157 60
3 158 50
4 159 1
5 160 9
6 161 110
从数据帧中提取样本行,参数sample
状态获取100%的frac=1
排成一排。这基本上是对数据帧进行洗牌- 使用
遍历无序数据帧iterrrows
print(df[df['ID'].isin(obid)])
输出:
[5, 6, 4, 1]
ID key acres
0 1 156 10
3 4 159 1
4 5 160 9
5 6 161 110
最终可能会出现这样的情况,即随机抽取选择了所有显示的行。如果最后绘制了
ID==6
,那么您将得到240英亩的总和。这样可以吗?是的,我可以处理。
ID key acres
0 1 156 10
3 4 159 1
4 5 160 9
5 6 161 110