下面给出了三种不同的实现,即查找IEnumerable <int>源的总和,以及源具有10,000个整数所花费的时间.
source.Aggregate(0, (result, element) => result + element);
Run Code Online (Sandbox Code Playgroud)
需要3毫秒
source.Sum(c => c);
Run Code Online (Sandbox Code Playgroud)
需要12毫秒
source.Sum();
Run Code Online (Sandbox Code Playgroud)
需要1毫秒
我想知道为什么第二次实施比第一次实施贵四倍.不应该与第三个实现相同.
我经常使用用过的pandas agg()函数来对data.frame的每一列运行汇总统计.例如,以下是产生均值和标准差的方法:
df = pd.DataFrame({'A': ['group1', 'group1', 'group2', 'group2', 'group3', 'group3'],
'B': [10, 12, 10, 25, 10, 12],
'C': [100, 102, 100, 250, 100, 102]})
>>> df
[output]
A B C
0 group1 10 100
1 group1 12 102
2 group2 10 100
3 group2 25 250
4 group3 10 100
5 group3 12 102
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,将各行发送到agg函数的顺序无关紧要.但请考虑以下示例,其中:
df.groupby('A').agg([np.mean, lambda x: x.iloc[1] ])
[output]
mean <lambda> mean <lambda>
A
group1 11.0 12 101 102
group2 17.5 25 175 250
group3 11.0 …Run Code Online (Sandbox Code Playgroud) 我想与Python解决方案共享这个特定的Apache Spark,因为它的文档很差.
我想用KEY计算K/V对(存储在Pairwise RDD中)的平均值.以下是示例数据的样子:
>>> rdd1.take(10) # Show a small sample.
[(u'2013-10-09', 7.60117302052786),
(u'2013-10-10', 9.322709163346612),
(u'2013-10-10', 28.264462809917358),
(u'2013-10-07', 9.664429530201343),
(u'2013-10-07', 12.461538461538463),
(u'2013-10-09', 20.76923076923077),
(u'2013-10-08', 11.842105263157894),
(u'2013-10-13', 32.32514177693762),
(u'2013-10-13', 26.249999999999996),
(u'2013-10-13', 10.693069306930692)]
Run Code Online (Sandbox Code Playgroud)
现在,下面的代码序列不是最佳的方法,但它确实有效.在我找到更好的解决方案之前,我正在做的事情.这并不可怕但是 - 正如你在答案部分看到的那样 - 有一种更简洁,有效的方式.
>>> import operator
>>> countsByKey = sc.broadcast(rdd1.countByKey()) # SAMPLE OUTPUT of countsByKey.value: {u'2013-09-09': 215, u'2013-09-08': 69, ... snip ...}
>>> rdd1 = rdd1.reduceByKey(operator.add) # Calculate the numerators (i.e. the SUMs).
>>> rdd1 = rdd1.map(lambda x: (x[0], x[1]/countsByKey.value[x[0]])) # Divide each SUM by …Run Code Online (Sandbox Code Playgroud) 我有一个数据框喜欢:
x <-
id1 id2 val1 val2 val3 val4
1 a x 1 9
2 a x 2 4
3 a y 3 5
4 a y 4 9
5 b x 1 7
6 b y 4 4
7 b x 3 9
8 b y 2 8
Run Code Online (Sandbox Code Playgroud)
我希望通过id1和id2汇总上面的内容.我希望能够同时获得val1,val2,val3,val4的平均值.
我该怎么做呢?
这是我目前拥有的,但它只适用于1列:
agg <- aggregate(x$val1, list(id11 = x$id1, id2= x$id2), mean)
names(agg)[3] <- c("val1") # Rename the column
Run Code Online (Sandbox Code Playgroud)
另外,如何重命名在上面给出的相同语句中作为均值输出的列
def stack_plot(data, xtick, col2='project_is_approved', col3='total'):
ind = np.arange(data.shape[0])
plt.figure(figsize=(20,5))
p1 = plt.bar(ind, data[col3].values)
p2 = plt.bar(ind, data[col2].values)
plt.ylabel('Projects')
plt.title('Number of projects aproved vs rejected')
plt.xticks(ind, list(data[xtick].values))
plt.legend((p1[0], p2[0]), ('total', 'accepted'))
plt.show()
def univariate_barplots(data, col1, col2='project_is_approved', top=False):
# Count number of zeros in dataframe python: /sf/answers/3607836501/
temp = pd.DataFrame(project_data.groupby(col1)[col2].agg(lambda x: x.eq(1).sum())).reset_index()
# Pandas dataframe grouby count: /sf/answers/1356991401/
temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']
temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']
temp.sort_values(by=['total'],inplace=True, ascending=False)
if top:
temp = temp[0:top]
stack_plot(temp, xtick=col1, col2=col2, col3='total')
print(temp.head(5))
print("="*50)
print(temp.tail(5))
univariate_barplots(project_data, 'school_state', 'project_is_approved', False) …Run Code Online (Sandbox Code Playgroud) 我想获得此记录的最大值.请帮我:
SELECT rest.field1
FROM mastertable AS m
INNER JOIN (
SELECT t1.field1 field1,
t2.field2
FROM table1 AS T1
INNER JOIN table2 AS t2 ON t2.field = t1.field
WHERE t1.field3=MAX(t1.field3)
-- ^^^^^^^^^^^^^^ Help me here.
) AS rest ON rest.field1 = m.field
Run Code Online (Sandbox Code Playgroud) 我目前正在使用DDD工作很多,并且在从其他聚合根加载/操作聚合根时遇到问题.
对于我模型中的每个聚合根,我也有一个存储库.存储库负责处理根的持久性操作.
假设我有两个聚合根,包含一些成员(实体和值对象).
AggregateRoot1和AggregateRoot2.
AggregateRoot1有一个引用AggregateRoot2的实体成员.
此外,当我在AggregateRoot1中的实体与AggregateRoot2之间创建关联时,是应该通过实体还是通过AggregateRoot2的存储库来完成?
希望我的问题有道理.
[编辑]
当前的解决方案
在Twith2Sugars的帮助下,我提出了以下解决方案:
如问题中所述,聚合根可以具有引用其他根的子项.将root2分配给root1的其中一个成员时,root1的存储库将负责检测此更改,并将其委派给root2的存储库.
public void SomeMethod()
{
AggregateRoot1 root1 = AggregateRoot1Repository.GetById("someIdentification");
root1.EntityMember1.AggregateRoot2 = new AggregateRoot2();
AggregateRoot1Repository.Update(root1);
}
public class AggregateRoot1Repository
{
public static void Update(AggregateRoot1 root1)
{
//Implement some mechanism to detect changes to referenced roots
AggregateRoot2Repository.HandleReference(root1.EntityMember1, root1.EntityMember1.AggregateRoot2)
}
}
Run Code Online (Sandbox Code Playgroud)
这只是一个简单的例子,没有Demeter法或其他最佳原则/实践包括:-)
进一步评论赞赏.
domain-driven-design aggregate loading repository aggregateroot
我在网上看到了一个AggregateException的例子,我正在试图弄清楚它是如何工作的,所以我编写了一个简单的例子,但由于某种原因我的代码不起作用
有人可以解释一下我的问题是什么
public static void Main()
{
try
{
Parallel.For(0, 500000, i =>
{
if (i == 10523)
throw new TimeoutException("i = 10523");
Console.WriteLine(i + "\n");
});
}
catch (AggregateException exception)
{
foreach (Exception ex in exception.InnerExceptions)
{
Console.WriteLine(ex.ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud) 之前已经讨论过这个问题,但是没有一个答案解决了我的具体问题,因为我正在处理内部和外部选择中的不同where子句.此查询在Sybase下执行得很好,但在SQL Server下执行时会在此帖子的标题中给出错误.查询很复杂,但查询的一般大纲是:
select sum ( t.graduates -
( select sum ( t1.graduates )
from table as t1
where t1.id = t.id and t1.group_code not in ('total', 'others' ) ) )
from table as t
where t.group_code = 'total'
Run Code Online (Sandbox Code Playgroud)
以下描述了我要解决的情况:
无论如何使用派生表或联接来重写它以获得相同的结果?
更新:我为我的具体问题创建了样本数据和3个解决方案(2个受sgeddes影响).我添加的那个涉及将相关子查询移动到FROM子句中的派生表.谢谢你的帮助!
我有一个类似于以下内容的表:
PropertyID Amount Type EndDate
--------------------------------------------
1 100 RENT null
1 50 WATER null
1 60 ELEC null
1 10 OTHER null
2 70 RENT null
2 10 WATER null
Run Code Online (Sandbox Code Playgroud)
将向物业收取多个物品,并且还会多次收费.例如,RENT可以向属性#1收费12次(超过一年),但是我唯一感兴趣的是ENDDATE为null(换句话说,当前)
我想实现:
PropertyId Amount
--------------------------
1 220
2 80
Run Code Online (Sandbox Code Playgroud)
我试图做这样的事情:
SELECT
propertyId,
SUM() as TOTAL_COSTS
FROM
MyTable
Run Code Online (Sandbox Code Playgroud)
但是,在SUM中我会被迫多次选择带回每种类型电荷的当前金额吗?我可以看到这变得混乱,我希望有一个更简单的解决方案
有任何想法吗?
aggregate ×10
python ×3
sql ×3
sql-server ×3
c# ×2
pandas ×2
t-sql ×2
apache-spark ×1
average ×1
exception ×1
linq ×1
loading ×1
performance ×1
r ×1
rdd ×1
repository ×1
sum ×1