我正在做探索性的數據分析,同時這樣做我使用相同的代碼行很多次。所以我才知道,爲什麼我不能寫這個函數。但我是新來的蟒蛇我不知道如何定義一個函數exactly.So請幫我.....如何在python中編寫函數?
的TextData是我的主要數據框和tonumber,smstext是我的變量
# subsetting the textdata
mesbytonum = textdata[['tonumber', 'smstext']]
# calculating the no.of messages by tonumber
messbytonum_freq = mesbytonum.groupby('tonumber').agg(len)
# resetting the index
messbytonum_freq.reset_index(inplace=True)
# making them in a descending order
messbytonum_freq_result = messbytonum_freq.sort(['smstext'], ascending=[0])
#calcuating percentages
messbytonum_freq_result['percentage'] = messbytonum_freq_result['smstext']/sum(messbytonum_freq_result['smstext'])
# considering top10
top10tonum = messbytonum_freq_result.head(10)
# top10tonum
我已經重複了類似的那種碼20左右次,所以我想寫上面的代碼,使我的代碼更小的功能。所以請幫助我如何定義。
在此先感謝
[檢查這個(https://docs.python.org/2/tutorial/controlflow.html#defining-functions) – 2015-03-31 15:16:50
http://stackoverflow.com/questions/14012076/how-to-write-a-function-that-returns-a-function-in-python – Jonathan 2015-03-31 15:26:02