假设有一列包含值
from, route, next, redirect...
现在,我想计算该列中有多少次Abc或其他名称,并在下一列中写入相应的计数。
Website
Abc
Abc
Abc
Xyz
Xyz
Pqr
Uvw
是否可以创建功能而无需手动计算每个网站?
答案 0 :(得分:2)
1)ave 使用结尾处“注释”中可重复显示的数据,我们可以使用ave
将length
应用于每个组:
transform(DF, Count = ave(seq_along(Website), Website, FUN = length))
给予:
Website Count
1 Abc 3
2 Abc 3
3 Abc 3
4 Xyz 2
5 Xyz 2
6 Pqr 1
7 Uvw 1
2)汇总或不重复:
aggregate(list(Count = 1:nrow(DF)), DF["Website"], length)
给予:
Website Count
1 Abc 3
2 Pqr 1
3 Uvw 1
4 Xyz 2
3)表:另一种方法是创建表而不是data.frame:
table(DF)
给予:
DF
Abc Pqr Uvw Xyz
3 1 1 2
4)xtabs ,或者我们可以使用xtabs
:
xtabs(DF)
给予:
Website
Abc Pqr Uvw Xyz
3 1 1 2
可复制形式的输入:
Lines <- "Website
Abc
Abc
Abc
Xyz
Xyz
Pqr
Uvw"
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE, strip.white = TRUE)
答案 1 :(得分:1)
带有 import json
import pyodbc
# Includes other imports
def query_db(query):
"""
Function that queries the required table in the DB
"""
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server}; \
SERVER=db.database.windows.net; \
DATABASE=DB; UID=id; PWD=pwd')
cnxn.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')
cur = cnxn.cursor()
cur.execute(query)
# Fetches the entire table ## This is causing the lagg
r = [dict( (cur.description[i][0], value) for i, value in enumerate(row) ) for row in cur.fetchall()]
cur.connection.close()
return(r)
@api_view(['GET'])
def get(request):
paginator = PageNumberPagination()
my_query = query_db("select * from Client_Table")
result_page = paginator.paginate_queryset(my_query, request)
json_output = json.dumps(result_page, cls=DjangoJSONEncoder)
return paginator.get_paginated_response(json_output)
的一个选项是tidyverse
add_count