① python 统计个数怎么统计
#-*-coding:cp936-*-
fruitfile=open(r"fruit.txt")
fruitdict={}
forlineinfruitfile.readlines():
fruit=line.split()[1]
iffruitdict.has_key(fruit):
fruitdict[fruit]+=1
else:
fruitdict[fruit]=1
fruitlist=[]
forkey,valueinfruitdict.items():
fruitlist.append((key,value))
fruitlist.sort(lambdaa,b:b[1],reverse=True)
iflen(fruitlist)>=3:
print"出现次数前三的水果:"
printfruitlist[0][0],fruitlist[0][1]
printfruitlist[1][0],fruitlist[1][1]
printfruitlist[2][0],fruitlist[2][1]
print" 所有水果出现次数:"
forkey,valueinfruitlist:
printkey,value
其中fruit.txt为文件名
② 如何高效地使用Python统计数据的频率
之前用 Python 写过一个脚本,用来处理上千万用户的一些数据,其中有一个需求是统计用户的某一数据的去重数量。为了加快程序的速度,我启用了多进程。但不幸的是,程序跑了近一个星期,还没处理完。这时,我感觉到了不对,于是开始查看程序的性能瓶颈。
对于统计去重数,我是将用户的数据放到一个列表中,然后用 len(set(data)) 去统计去重数量。刚开始我以为这的数据量并不大,每个用户的数据不会过百,我并没有注意到有的用户会有上万条的数据,因此消耗了大量的时间(其实我的脚本消耗时间最大的地方是因为从远程 redis 中取大量数据时发生长时间的阻塞,甚至连接超时,最后我采用的方式分而治之,每次取少量的数据,这样大大的提高了性能)。
为了做优化,我开始寻求高效的方法。我发现,有大量的人认为采用字典效率会更高,即:
data_unique = {}.fromkeys(data).keys() len(data_unique)
于是,我做了下测试:
In [1]: import random In [2]: data = [random.randint(0, 1000) for _ in xrange(1000000)] In [3]: %timeit len(set(data)) 10 loops, best of 3: 39.7 ms per loop In [4]: %timeit len({}.fromkeys(data).keys()) 10 loops, best of 3: 43.5 ms per loop
由此可见,采用字典和采用集合的性能是差不多的,甚至可能还要慢些。
在 Python 中其实有很多高效的库,例如用 numpy、pandas 来处理数据,其性能接近于 C 语言。那么,我们就用 numpy 和 pandas 来解决这个问题,这里我还比较了获取去重数据的性能,代码如下:
import collections import random as py_random import timeit import numpy.random as np_random import pandas as pd DATA_SIZE = 10000000 def py_cal_len(): data = [py_random.randint(0, 1000) for _ in xrange(DATA_SIZE)] len(set(data)) def pd_cal_len(): data = np_random.randint(1000, size=DATA_SIZE) data = pd.Series(data) data_unique = data.value_counts() data_unique.size def py_count(): data = [py_random.randint(0, 1000) for _ in xrange(DATA_SIZE)] collections.Counter(data) def pd_count(): data = np_random.randint(1000, size=DATA_SIZE) data = pd.Series(data) data.value_counts() # Script starts from here if __name__ == "__main__": t1 = timeit.Timer("py_cal_len()", setup="from __main__ import py_cal_len") t2 = timeit.Timer("pd_cal_len()", setup="from __main__ import pd_cal_len") t3 = timeit.Timer("py_count()", setup="from __main__ import py_count") t4 = timeit.Timer("pd_count()", setup="from __main__ import pd_count") print t1.timeit(number=1) print t2.timeit(number=1) print t3.timeit(number=1) print t4.timeit(number=1)
运行结果:
12.438587904 0.435907125473 14.6431810856 0.258564949036
利用 pandas 统计数据的去重数和去重数据,其性能是 Python 原生函数的 10 倍以上。
③ 如何使用python做统计分析
Shape Parameters
形态参数
While a general continuous random variable can be shifted and scaled
with the loc and scale parameters, some distributions require additional
shape parameters. For instance, the gamma distribution, with density
γ(x,a)=λ(λx)a−1Γ(a)e−λx,
requires the shape parameter a. Observe that setting λ can be obtained by setting the scale keyword to 1/λ.
虽然一个一般的连续随机变量可以被位移和伸缩通过loc和scale参数,但一些分布还需要额外的形态参数。作为例子,看到这个伽马分布,这是它的密度函数
γ(x,a)=λ(λx)a−1Γ(a)e−λx,
要求一个形态参数a。注意到λ的设置可以通过设置scale关键字为1/λ进行。
Let’s check the number and name of the shape parameters of the gamma
distribution. (We know from the above that this should be 1.)
让我们检查伽马分布的形态参数的名字的数量。(我们知道从上面知道其应该为1)
>>>
>>> from scipy.stats import gamma
>>> gamma.numargs
1
>>> gamma.shapes
'a'
Now we set the value of the shape variable to 1 to obtain the
exponential distribution, so that we compare easily whether we get the
results we expect.
现在我们设置形态变量的值为1以变成指数分布。所以我们可以容易的比较是否得到了我们所期望的结果。
>>>
>>> gamma(1, scale=2.).stats(moments="mv")
(array(2.0), array(4.0))
Notice that we can also specify shape parameters as keywords:
注意我们也可以以关键字的方式指定形态参数:
>>>
>>> gamma(a=1, scale=2.).stats(moments="mv")
(array(2.0), array(4.0))
Freezing a Distribution
冻结分布
Passing the loc and scale keywords time and again can become quite
bothersome. The concept of freezing a RV is used to solve such problems.
不断地传递loc与scale关键字最终会让人厌烦。而冻结RV的概念被用来解决这个问题。
>>>
>>> rv = gamma(1, scale=2.)
By using rv we no longer have to include the scale or the shape
parameters anymore. Thus, distributions can be used in one of two ways,
either by passing all distribution parameters to each method call (such
as we did earlier) or by freezing the parameters for the instance of the
distribution. Let us check this:
通过使用rv我们不用再更多的包含scale与形态参数在任何情况下。显然,分布可以被多种方式使用,我们可以通过传递所有分布参数给对方法的每次调用(像我们之前做的那样)或者可以对一个分布对象冻结参数。让我们看看是怎么回事:
>>>
>>> rv.mean(), rv.std()
(2.0, 2.0)
This is indeed what we should get.
这正是我们应该得到的。
Broadcasting
广播
The basic methods pdf and so on satisfy the usual numpy broadcasting
rules. For example, we can calculate the critical values for the upper
tail of the t distribution for different probabilites and degrees of
freedom.
像pdf这样的简单方法满足numpy的广播规则。作为例子,我们可以计算t分布的右尾分布的临界值对于不同的概率值以及自由度。
>>>
>>> stats.t.isf([0.1, 0.05, 0.01], [[10], [11]])
array([[ 1.37218364, 1.81246112, 2.76376946],
[ 1.36343032, 1.79588482, 2.71807918]])
Here, the first row are the critical values for 10 degrees of freedom
and the second row for 11 degrees of freedom (d.o.f.). Thus, the
broadcasting rules give the same result of calling isf twice:
这里,第一行是以10自由度的临界值,而第二行是以11为自由度的临界值。所以,广播规则与下面调用了两次isf产生的结果相同。
>>>
>>> stats.t.isf([0.1, 0.05, 0.01], 10)
array([ 1.37218364, 1.81246112, 2.76376946])
>>> stats.t.isf([0.1, 0.05, 0.01], 11)
array([ 1.36343032, 1.79588482, 2.71807918])
If the array with probabilities, i.e, [0.1, 0.05, 0.01] and the array of
degrees of freedom i.e., [10, 11, 12], have the same array shape, then
element wise matching is used. As an example, we can obtain the 10% tail
for 10 d.o.f., the 5% tail for 11 d.o.f. and the 1% tail for 12 d.o.f.
by calling
但是如果概率数组,如[0.1,0.05,0.01]与自由度数组,如[10,11,12]具有相同的数组形态,则元素对应捕捉被作用,我们可以分别得到10%,5%,1%尾的临界值对于10,11,12的自由度。
>>>
>>> stats.t.isf([0.1, 0.05, 0.01], [10, 11, 12])
array([ 1.37218364, 1.79588482, 2.68099799])
Specific Points for Discrete Distributions
离散分布的特殊之处
Discrete distribution have mostly the same basic methods as the
continuous distributions. However pdf is replaced the probability mass
function pmf, no estimation methods, such as fit, are available, and
scale is not a valid keyword parameter. The location parameter, keyword
loc can still be used to shift the distribution.
离散分布的简单方法大多数与连续分布很类似。当然像pdf被更换为密度函数pmf,没有估计方法,像fit是可用的。而scale不是一个合法的关键字参数。Location参数,关键字loc则仍然可以使用用于位移。
The computation of the cdf requires some extra attention. In the case of
continuous distribution the cumulative distribution function is in most
standard cases strictly monotonic increasing in the bounds (a,b) and
has therefore a unique inverse. The cdf of a discrete distribution,
however, is a step function, hence the inverse cdf, i.e., the percent
point function, requires a different definition:
ppf(q) = min{x : cdf(x) >= q, x integer}
Cdf的计算要求一些额外的关注。在连续分布的情况下,累积分布函数在大多数标准情况下是严格递增的,所以有唯一的逆。而cdf在离散分布,无论如何,是阶跃函数,所以cdf的逆,分位点函数,要求一个不同的定义:
ppf(q) = min{x : cdf(x) >= q, x integer}
For further info, see the docs here.
为了更多信息可以看这里。
We can look at the hypergeometric distribution as an example
>>>
>>> from scipy.stats import hypergeom
>>> [M, n, N] = [20, 7, 12]
我们可以看这个超几何分布的例子
>>>
>>> from scipy.stats import hypergeom
>>> [M, n, N] = [20, 7, 12]
If we use the cdf at some integer points and then evaluate the ppf at
those cdf values, we get the initial integers back, for example
如果我们使用在一些整数点使用cdf,它们的cdf值再作用ppf会回到开始的值。
>>>
>>> x = np.arange(4)*2
>>> x
array([0, 2, 4, 6])
>>> prb = hypergeom.cdf(x, M, n, N)
>>> prb
array([ 0.0001031991744066, 0.0521155830753351, 0.6083591331269301,
0.9897832817337386])
>>> hypergeom.ppf(prb, M, n, N)
array([ 0., 2., 4., 6.])
If we use values that are not at the kinks of the cdf step function, we get the next higher integer back:
如果我们使用的值不是cdf的函数值,则我们得到一个更高的值。
>>>
>>> hypergeom.ppf(prb + 1e-8, M, n, N)
array([ 1., 3., 5., 7.])
>>> hypergeom.ppf(prb - 1e-8, M, n, N)
array([ 0., 2., 4., 6.])
④ 如何用Python写一个抓取天天基金网上每个基金经理业绩的爬虫
建议使用软件,操作简单,可视化程度高,爬取数据速度快,又不需要编程基础,小白福音呀
⑤ 如何用python写一个爬虫统计淘宝某件商品的销量
淘宝有相应的API可以查询商品销量,但似乎是收费的。
还有一种办法就是,抓取商品详情页面内容,提取出销量。
⑥ python怎么实现统计百分比
>>>rate=0.23
>>>print("分类正确率是:%.2f%%"%(rate*100))
分类正确率是:23.00%
>>>
保留几位小数自己看着办
⑦ 如何使用python对基金投资收益进行回测
详细建议您可以去看看掘金量化的Python接口文档,我们team有位大神挺懒的就是用掘金来做回测,免费的~回测是否具有统计意义看你的策略逻辑和交易样本的数量。个人认为可以直观地观测策略的盈亏特性,如适合什么属性的标的,在怎样的市场环境下能盈利(或亏损)。因此对未来行情的表现具有一定指导意义。
要注意的是,参数拟合好后把策略扔到样本外的历史行情观察表现,评估策略的适应性和泛化能力。
⑧ 用Python怎么统计一个列表的元素种类和各个种类的个数
统计一个列表中每一个元素的个数在Python里有两种实现方式,
第一种是新建一个dict,键是列表中的元素,值是统计的个数,然后遍历list。
items=["cc","cc","ct","ct","ac"]
count={}
foriteminitems:
count[item]=count.get(item,0)+1
print(count)
#{'ac':1,'ct':2,'cc':2}
之中用到了一个小技巧,当dict中不还没有统计过一个元素时,直接索引count[item]会报错,而使用get方法count.get(item, 0)能够设置索引不存在的键时返回0。
第二种是使用Python内置的函数。统计元素的个数是一种非常常见的操作,Python的collection包里已经有一个Counter的类,大致实现了上面的功能。
fromcollectionsimportCounter
items=["cc","cc","ct","ct","ac"]
count=Counter(items)
print(count)
#Counter({'ct':2,'cc':2,'ac':1})
⑨ 如何用Python写一个抓取天天基金网上每个基金经
用python写抓取天天基金的方法有很多呀~
但是,不清楚你具体要抓取什么内容。
写了一个最简单的例子:3行代码就可以抓一个包含所有开放基金数据的表格
代码如下:
importpandas
data=pandas.read_html('http://fund.eastmoney.com/fund.html#os_0;isall_1;ft_|;pt_1')
data[2].to_csv('天天基金.csv')
运行结果:
这应该是最简单神奇的代码了吧。前提是要安装好pandas哦,灵感来自yqxmf.top
⑩ 用python实现如下统计功能
你这个问题的难点在于不知道水果到底有多少种,所以需要先遍历每一行,获取全部的水果类型放入列表,最后用set去重,得到有多少种水果种类。然后重新打开文本读取,再统计水果重量。
代码如下:
#打开文本统计水果种类
file=open("test.txt",encoding="utf-8")
fruits_list=[]
whileTrue:
str=file.readline()
iflen(str)==0:
break
list1=str.split("|")
fruits=list1[3]
fruits_list.append(fruits)
fruits_list=list(set(fruits_list))
file.close()
#创建字典,key为水果品质,value为0
dic={}
foriinfruits_list:
dic[i]=0
print(dic)
#再次打开文件
file=open("test.txt",encoding="utf-8")
whileTrue:
str=file.readline()
iflen(str)==0:
break
list2=str.split("|")
foriindic:
ifi==list2[3]:
dic[i]=dic[i]+int(list2[4])
file.close()
print(dic)