我有这个数据框:
mob.columns
Out[806]: Index([u'country', u'maxterm', u'quantity'], dtype='object')
以下是一些数据:
mob.head(5)
Out[807]:
country maxterm quantity
0 China aled 44
1 China fanx 77
2 China grrx 12
3 China hldo 13
4 China jnmp 29
创建新列的最简单方法是,每列上列出的数量与每个国家/地区的所有数量之和的比率是多少?我正在尝试groupby和pivot并制作lambda函数。这种尝试
mob.groupby(['country', 'maxterm'])['quantity'].apply(lambda x: x / float(sum(x)) )
没有工作,只输出了一堆1。如果我可以在原始数据框中创建一个新列,那将是最好的。
答案 0 :(得分:4)
使用mob.quantity / mob.groupby('country').quantity.transform('sum')
0 0.251429
1 0.440000
2 0.068571
3 0.074286
4 0.165714
Name: quantity, dtype: float64
assign
使用mob.assign(ratio=mob.groupby('country').quantity.transform(lambda x: x / x.sum()))
country maxterm quantity ratio
0 China aled 44 0.251429
1 China fanx 77 0.440000
2 China grrx 12 0.068571
3 China hldo 13 0.074286
4 China jnmp 29 0.165714
%timeit mob.quantity.values / mob.groupby('country').quantity.transform('sum').values
%timeit mob.groupby('country').quantity.transform(lambda x: x / x.sum())
%timeit mob.quantity / mob.groupby('country').quantity.transform('sum')
1000 loops, best of 3: 956 µs per loop
1000 loops, best of 3: 1.53 ms per loop
1000 loops, best of 3: 1.03 ms per loop
计算选择
$uploaddir = __DIR__ . '/img/';
echo $_FILES['navpic']['error'];
if($_FILES['navpic']['size'] != 0) {
$navpic = $uploaddir . "navpic.png";
if($_FILES['navpic']['size'] < 1000000) {
if (move_uploaded_file($_FILES['navpic']['tmp_name'], $navpic)) {
$navpicupload = 0;
} else
$navpicupload = 1;
} else {
$navpicupload = 2;
}
} else {
$navpicupload = 1;
}