學習筆記,僅供參考,覺得哪裏不錯就記哪裏
使用工具:Jupyter Notebook(IPython notebook)
學習書目:《python編程從數據分析到數據編程》–朝樂門;
文章目錄
isinstance方法
isinstance() 函數來判斷一個對象是否是一個已知的類型,類似 type()。
-
isinstance() 與 type() 區別
-
type() 不會認爲子類是一種父類類型,不考慮繼承關係。
-
isinstance() 會認爲子類是一種父類類型,考慮繼承關係。
-
如果要判斷兩個類型是否相同推薦使用 isinstance()。
-
- 舉個例子
輸入:
list1 = [1, 2, 3]
isinstance(list1, list)
int1 = 100
isinstance(int1, int)
輸出:
True
True
科學計數法
- 舉個例子
輸入:
1.23e2
輸出:
123.0
數據類型
查看python關鍵字
- 舉個例子
輸入:
import keyword
keyword.kwlist
輸出:
['False',
'None',
'True',
'and',
'as',
'assert',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
查看已定義的所有變量
- 舉個例子
輸入:
dir()
輸出:
['In',
'InteractiveShell',
'Out',
'_',
'_1',
'_10',
'_11',
'_12',
'_13',
'_14',
'_15',
'_16',
'_19',
'_2',
'_20',
'_21',
'_22',
'_3',
'_4',
'_5',
'_6',
'_7',
'_8',
'_9',
'__',
'___',
'__builtin__',
'__builtins__',
'__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_dh',
'_i',
'_i1',
'_i10',
'_i11',
'_i12',
'_i13',
'_i14',
'_i15',
'_i16',
'_i17',
'_i18',
'_i19',
'_i2',
'_i20',
'_i21',
'_i22',
'_i23',
'_i3',
'_i4',
'_i5',
'_i6',
'_i7',
'_i8',
'_i9',
'_ih',
'_ii',
'_iii',
'_oh',
'_sh',
'exit',
'get_ipython',
'int1',
'keyword',
'list1',
'quit',
'test']
刪除變量
我們可以用del刪除變量x,但是需要注意的是,del是語句,而不是函數,寫成del(x)會報錯。
- 舉個例子
刪除變量x:
del x
if與三元運算符
語法:
item = "變量1" if a > b else "變量2"
上面這段代碼表達的意思是,如果a>b的結果爲真,則item被賦值爲"變量1",如果爲假,則item被賦值爲"變量2"
count方法
字符串中的應用
count()方法用於統計字符串裏某個字符出現的次數.
語法:
str.count(sub, start= 0,end=len(string))
#sub:搜索的子字符串
#start:字符串開始搜索的位置,默認爲第一個字符,第一個字符索引值爲0。
#end:字符串中結束搜索的位置,字符中第一個字符的索引爲 0,默認爲字符串的最後一個位置。
- 舉個例子
輸入:
"aaabbc".count("a")
輸出:
3
元祖中的應用
在python元組中,count() 方法用於統計某個元素在元祖中出現的次數。
語法:
T.count(obj)
#obj:元祖中統計的對象
- 舉個例子
輸入:
T = (10, 'Google', 10, 'Google', 10);
T.count('Google')
輸出:
2
列表中的應用
在python列表中,count() 方法用於統計某個元素在列表中出現的次數。
語法:
list.count(obj)
#obj:列表中統計的對象
- 舉個例子
輸入:
list1 = list("AnhuiCaiJingDaXue")
list1.count("i")
輸出:
3
列表中的sort應用
在列表中,我們可以按照字符串首字母順順序排序,也可以利用lambda表達式,指定字符串長度或者字符串中不同元素的數量作爲衡量排序的標準。
- 舉個例子
In [22]: str1 = ["abbee", "bbbbffff", "python", "c"]
In [23]: str1.sort()
In [24]: str1
Out[24]: ['abbee', 'bbbbffff', 'c', 'python']
In [25]: str1.sort(key = lambda x : len(x))
In [26]: str1
Out[26]: ['c', 'abbee', 'python', 'bbbbffff']
In [29]: str1.sort(key = lambda x : len(set(x)))
In [30]: str1
Out[30]: ['c', 'bbbbffff', 'abbee', 'python']
定義字典時出現重複的鍵
如果在我們定義字典時,兩個values出現相同的key,會發生什麼事情呢?情看下面的代碼:
In [31]: {"a":3, "a":2, 10:"hhh"}
Out[31]: {'a': 2, 10: 'hhh'}
數據科學中,常用的基礎包
在數據分析和數據科學項目中,常用的基礎包包括如下幾種: