① 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)