Python常用方法合集

获取工作路径

FileDir = os.getcwd() + "\\"#当前工作路径
if not os.path.exists(FileDir): 
    os.makedirs(FileDir)#创建目录
    FileDir = FileDir + "\\"
ResultFileDir = FileDir+"Result\\"
DataFileDir = FileDir + "Data\\"
pwd = os.getcwd()
当前文件的父路径:
father_path=os.path.abspath(os.path.dirname(pwd)+os.path.sep+".")
#当前文件的前两级路径:
grader_father=os.path.abspath(os.path.dirname(pwd)+os.path.sep+"..")

每列空值计数

df.isnull().sum()

列值条件替换

df['sex'] = df['sex'].map({'female':0,'male':1}).astype(int)
df.loc[(df['height'] <= 200) & (df['height'] >= 180),'label'] = 'a'

array格式转换

arr.astype(np.float64)

zip

x = [1,2,3]
y = [4,5,6]
z = [7,8,9]
xyz = zip(x,y,z)
>>>[(1,4,7),(2,5,8),(3,6,9)]

各值出现频率

obj.values_counts()

字符串后缀匹配

#输入一个字符串一个标签,对这个字符串的后续和标签进行匹配
def endwith(s,*endstring):
   resultArray = map(s.endswith,endstring)
   if True in resultArray:
       return True
   else:
       return False

猜你喜欢

转载自blog.csdn.net/changyan_123/article/details/81273851