【python】一些python用法规律笔记

2022-10-31,,,

作为本科用了多年MATLAB的工科生,学起来python有些似曾相识但也有些不习惯的地方。

在这里总结一下,慢慢整理,希望能巩固python语法

一、前闭后开

这个是和MATLAB很大不同。不论是range还是数组的切片等,python在这里都是前闭后开原则

查看代码

range(6, 11) # [6, 7, 8, 9, 10]
range(1, 10, 2) # [1, 3, 5, 7, 9]
range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] a = range(1,10)
b = a[1:3]
import numpy
b= numpy.array(b)
b # [2,3]

二、Pandas DataFrame

testdf3 = pd.DataFrame(
{"A": np.arange(5),
"B": pd.Timestamp("20171129"),
"C": pd.Series(1, index =np.arange(5), dtype = "float32"),
"D": np.array([3]*5),
"E": pd.Categorical(["test", "train", "test", "train","test"]),
"F": 'foo'})

行操作:

testdf3.iloc[0] # pandas series
testdf3.iloc[[0]] # dataframe testdf3[2:3] # data frame
testdf3.iloc[2:3] # data frame

列操作:

testdf3['A'] # 单独一列是个series
testdf3.loc[:,'A'] # 同上,但比较复杂,一般不用
testdf3.iloc[:,0] # 同上,可以在不知道列名的时候用 testdf3[['A']] #单独一列是个df
testdf3.loc[:,['A']] # 同上,但比较复杂,一般不用
testdf3.iloc[:,[0]] # 同上,可以在不知道列名的时候用 testdf3[['A','C']] # DF, 指定某几列,直接用列名
testdf3.loc[:,['A','C']] # 同上,但比较复杂,一般不用
testdf3.iloc[:,[0,2]] # 同上,可以在不知道列名的时候用 '''取指定的连续几列,不能偷懒了,必须用.loc'''
testdf3.loc[:,'A':'D'] #指定连续列,用列名
testdf3.iloc[:,0:4] # 指定连续列,用数字

同时取行和列:

'''第一种情况,列索引用数字'''
testdf3.iloc[[1,3],[0]] # dataframe
testdf3.iloc[[1,3],0] # series
testdf3.iloc[[1,3],1:3] # dataframe
testdf3.iloc[[1,3],[1,3]] '''第二种情况,列索引用列名'''
testdf3.loc[1,["A","D"]] # series 对应上述1.1
testdf3.loc[[1],["A","D"]] # df 对应上述1.1
testdf3.loc[[1,3],"A":"D"] # df 对应上述1.2
testdf3.loc[[1,3],["A","D"]] # df 对应上述1.3

【python】一些python用法规律笔记的相关教程结束。

《【python】一些python用法规律笔记.doc》

下载本文的Word格式文档,以方便收藏与打印。