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

作为本科用了多年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

 

posted @   xiaoxiao_sjtu  阅读(107)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示