python常用操作总结

Python zip()

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

https://www.runoob.com/python/python-func-zip.html

 

Python索引

iloc根据位置 ,行号

loc根据index

https://www.cnblogs.com/soloveu/p/10049096.html

 

 

python @ 函数装饰器

http://c.biancheng.net/view/2270.html

https://blog.csdn.net/u012759262/article/details/79749299

当程序使用“@函数”(比如函数 A)装饰另一个函数(比如函数 B)时,实际上完成如下两步:

将被修饰的函数(函数 B)作为参数传给 @ 符号引用的函数(函数 A)。

将函数 B 替换(装饰)成第 1 步的返回值

 

@staticmethod

python中的staticmethod 主要是方便将外部函数集成到类体中,美化代码结构,重点在不需要类实例化的情况下调用方法

如果你去掉staticmethod,在方法中加self也可以通过实例化访问方法也是可以集成代码

https://blog.csdn.net/u013066730/article/details/56670685

https://www.cnblogs.com/elie/p/5876210.html

 

assert 报告异常

assert condition

用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于:

if not condition:

    raise AssertionError()

https://www.cnblogs.com/hezhiyao/p/7805278.html

 

train.csv中有 图片id, 图片url,  landmark_id地标标签

 

itertools

迭代相关的一些函数

chain()可以把一组迭代对象串联起来,形成一个更大的迭代器

groupby()把迭代器中相邻的重复元素挑出来放在一起

 

https://www.liaoxuefeng.com/wiki/897692888725344/983420006222912

 

python中pip 安装、升级、升级固定的包

https://blog.csdn.net/qq_15260769/article/details/80731407

pip install 安装包名

pip install --upgrade 要升级的包名

pip uninstall 要卸载的包名

pip install --ignore-installed 要强制升级的包名

 

 

终端运行python代码:

关闭命令行窗口的快捷键如下:Ctrl + d

进入python环境:在命令行中直接输入python即进入了python的编辑环境。进入环境后最明显的提示是:光标由~$变成>>>。

退出python环境:使用ctrl +d的方式退出python环境。回到命令行环境。

在python环境中输入多行函数:在语句的末尾输入英文的;\即可实现换行。

例如:

def weight_variable(shape):

 initial = tf.truncated_normal(shape, stddev=0.1);\

 return tf.Variable(initial);\

注意:输入函数块时注意缩进

 

 

Python显示图像:

import matplotlib.pyplot as plt

plt.imshow(img)

 

Python|list,dict和DataFrame之间的相互转换

https://www.jianshu.com/p/22da8bb6c568

 

Python Dataframe转List

https://www.cnblogs.com/wq14061023/p/9002281.html

from pandas import read_csv

 

dataframe = read_csv(r'url', nrows = 86400, usecols = [0,], engine='python')

#nrows:读取行数,usecols=[n,]:仅读取第n列,usecols=[a,b,c]:读取a、b、c列

dataset = dataframe.values

 

List = []

for k in dataset:

    for j in k:

        List.append(j)

 

print(dataframe[0:3])

print(dataset[0:3])

print(List[0:3])

 

python字符串查找的四种方法

https://blog.csdn.net/tan197/article/details/82708553

 

python查找元素在列表中位置

p=list.index(value)

list为列表的名字

value为查找的值

p为value在list的位置

 

Python统计列表元素出现次数

https://blog.csdn.net/weixin_40604987/article/details/79292493

def all_list(arr):

    result = {}

    for i in set(arr):

        result[i] = arr.count(i)

    return result

 

# 结果:{0: 1, 1: 2, 2: 3, 3: 2}

 

查看list的shape

print(np.array(dict_landmark_unique).shape)

 

 

keys = sorted(dict_landmark_unique, key=lambda k: dict_landmark_unique[k],reverse= True)

 

print(item,dict_landmark_unique[item])

 

python的CSV文件读写 和 DataFrame

https://blog.csdn.net/bq_cui/article/details/81274202

https://www.cnblogs.com/wqpkita/p/7285418.html

https://blog.csdn.net/baidu_33718858/article/details/83758878

## submission
sample_submission = pd.read_csv('../dataset/retrieval_sample_submission.csv')
print("make sure the submmison rows: ", len(sample_submission))
test_id_list = sample_submission.id

ids = []
images = []
for ind, test in enumerate(test_image_id):
    ids.append(test)
    pred = all_predictions[ind]
    tmp = [str(name) for name in pred[:100]]
    images.append(" ".join(tmp))

submission = pd.DataFrame({'id': ids, 'images': images})
target = pd.DataFrame({"id":test_id_list})
submission = pd.merge(target, submission, how='left', on='id')
submission.to_csv("submission_retrieve_QE.csv", index=False, columns=['id', 'images'])

 

python 把几个DataFrame合并成一个DataFrame——merge,append,join,conca

https://blog.csdn.net/qq_42707449/article/details/81116656

ids_df = pd.DataFrame({"id": ids})
images_df = pd.DataFrame({"images": images})
submission = pd.concat([ids_df, images_df], axis=1)

 

python3中argparse模块

https://www.cnblogs.com/dengtou/p/8413609.html

1、定义:argparse是python标准库里面用来处理命令行参数的库

2、命令行参数分为位置参数和选项参数:

        位置参数就是程序根据该参数出现的位置来确定的

                如:[root@openstack_1 /]# ls root/    #其中root/是位置参数

        选项参数是应用程序已经提前定义好的参数,不是随意指定的

                如:[root@openstack_1 /]# ls -l    # -l 就是ls命令里的一个选项参数

 3、使用步骤:

(1)import argparse    首先导入模块

(2)parser = argparse.ArgumentParser()  创建一个解析对象

(3)parser.add_argument()    向该对象中添加你要关注的命令行参数和选项

(4)parser.parse_args()    进行解析

 

python 复制/移动文件

https://www.cnblogs.com/iois/p/7258686.html

import os,shutil

 

def mymovefile(srcfile,dstfile):

    if not os.path.isfile(srcfile):

        print "%s not exist!"%(srcfile)

    else:

        fpath,fname=os.path.split(dstfile)    #分离文件名和路径

        if not os.path.exists(fpath):

            os.makedirs(fpath)                #创建路径

        shutil.move(srcfile,dstfile)          #移动文件

        print "move %s -> %s"%( srcfile,dstfile)

 

def mycopyfile(srcfile,dstfile):

    if not os.path.isfile(srcfile):

        print "%s not exist!"%(srcfile)

    else:

        fpath,fname=os.path.split(dstfile)    #分离文件名和路径

        if not os.path.exists(fpath):

            os.makedirs(fpath)                #创建路径

        shutil.copyfile(srcfile,dstfile)      #复制文件

        print "copy %s -> %s"%( srcfile,dstfile)

 

srcfile='/Users/xxx/git/project1/test.sh'

dstfile='/Users/xxx/tmp/tmp/1/test.sh'

 

mymovefile(srcfile,dstfile)

 

python tolist()方法

https://www.cnblogs.com/Aaron12/p/9042687.html

https://blog.csdn.net/lilong117194/article/details/78437224

https://blog.csdn.net/nageaixiaodenanhai/article/details/79828895

但是当矩阵是一维的时候,就不同了,所以一维矩阵经常会有tolist()[0]

>>> from numpy import *

>>> a1 = [[1,2,3],[4,5,6]] #列表

>>> a2 = array(a1) #数组

>>> a2

array([[1, 2, 3],

       [4, 5, 6]])

>>> a3 = mat(a1) #矩阵

>>> a3

matrix([[1, 2, 3],

        [4, 5, 6]])

>>> a4 = a2.tolist()

>>> a4

[[1, 2, 3], [4, 5, 6]]

>>> a5 = a3.tolist()

>>> a5

[[1, 2, 3], [4, 5, 6]]

>>> a4 == a5

True

 

Python for和枚举和lambda

list_pre_submission = [pre_submission.iloc[i, :] for i in range(len(pre_submission))]

 

locations_2_to_use = np.array([locations_2[i,] for i in range(num_features_2)
                               if indices[i] != num_features_1])

 

枚举enumerate

for ind, test in enumerate(test_image_id):
    ids.append(test)
    pred = all_predictions[ind]
    tmp = [str(name) for name in pred[:100]]
    images.append(" ".join(tmp))

 

 

Tqdm python进度条包

https://blog.csdn.net/zkp_987/article/details/81748098

 

python学习笔记——multiprocessing 多进程组件 进程池Pool

https://www.cnblogs.com/gengyi/p/8620853.html

在使用Python进行系统管理时,特别是同时操作多个文件目录或者远程控制多台主机,并行操作可以节约大量时间,如果操作的对象数目不大时,还可以直接适用Process类动态生成多个进程,几十个尚可,若上百个甚至更多时,手动限制进程数量就显得特别繁琐,此时进程池就显得尤为重要。

进程池Pool类可以提供指定数量的进程供用户调用,当有新的请求提交至Pool中时,若进程池尚未满,就会创建一个新的进程来执行请求;若进程池中的进程数已经达到规定的最大数量,则该请求就会等待,直到进程池中有进程结束,才会创建新的进程来处理该请求。

进程池不用频繁创建和销毁进程

 

pickle库

https://www.php.cn/python-tutorials-372984.html

为什么需要序列化和反序列化这一操作呢?

  1. 便于存储。序列化过程将文本信息转变为二进制数据流。这样就信息就容易存储在硬盘之中,当需要读取文件的时候,从硬盘中读取数据,然后再将其反序列化便可以得到原始的数据。在Python程序运行中得到了一些字符串、列表、字典等数据,想要长久的保存下来,方便以后使用,而不是简单的放入内存中关机断电就丢失数据。python模块大全中的Pickle模块就派上用场了,它可以将对象转换为一种可以传输或存储的格式。
  2. loads()函数执行和load() 函数一样的反序列化。取代接受一个流对象并去文件读取序列化后的数据,它接受包含序列化后的数据的str对象, 直接返回的对象

python多线程

https://www.cnblogs.com/pythonxiaokang/p/5606003.html

进程与线程之间的关系

线程是属于进程的,线程运行在进程空间内,同一进程所产生的线程共享同一内存空间,当进程退出时该进程所产生的线程都会被强制退出并清除。线程可与属于同一进程的其它线程共享进程所拥有的全部资源,但是其本身基本上不拥有系统资源,只拥有一点在运行中必不可少的信息(如程序计数器、一组寄存器和栈)。

 

 

进程池Pool的imap方法

https://www.jianshu.com/p/4c4ca5bccc09

iter = pool.imap(fn, data)

 

python异常处理

https://www.runoob.com/python/python-exceptions.html

try:

<语句>        #运行别的代码

except <名字>:

<语句>        #如果在try部份引发了'name'异常

except <名字>,<数据>:

<语句>        #如果引发了'name'异常,获得附加的数据

else:

<语句>        #如果没有异常发生

 

Python item()

https://blog.csdn.net/weixin_38664232/article/details/90763042

item()方法把字典中每对key和value组成一个元组,并把这些元组放在列表中返回。

key接收了字典的key,value接收了字典的value值

#from keras.datasets import mnist

person={'name':'lizhong','age':'26','city':'BeiJing','blog':'www.jb51.net'}

for key,value in person.items():

   

    print('key=',key,'value=',value)

如果只有一个参数接收

#from keras.datasets import mnist

person={'name':'lizhong','age':'26','city':'BeiJing','blog':'www.jb51.net'}

for x in person.items():

 

    print('x=',x)

也可以打包

dict_id2landmark = {id: landmark for id, landmark in zip(train_csv.id, train_csv.landmark_id)}

 

python查找列表中某个值的位置

p=list.index(value)

list为列表的名字

value为查找的值

p为value在list的位置

 

python numpy——.npy和.npz文件

https://www.cnblogs.com/Lilu-1226/p/9768368.html

1.npy文件——Numpy专用的二进制格式

np.load()和np.save()是读写磁盘数组数据的两个重要函数。使用时,数组会以未压缩的原始二进制格式保存在扩展名为.npy的文件中。

2.npz文件——压缩文件

扩展名为.npz的压缩文件,它包含多个与保存的数组对应的npy文件(由save()函数保存),文件名对应数组名
读取.npz文件时使用np.load()函数,返回的是一个类似于字典的对象,因此可以通过数组名作为关键字对多个数组进行访问

 

Python编程之numpy库函数in1d的使用

https://blog.csdn.net/qq_35751790/article/details/78660290

in1d函数与excel中vlookup函数和MATLAB中ismember函数有相似之处。其作用在于在序列B中寻找与序列A相同的值,并返回一逻辑值(True,False)或逻辑值构成的向量。具体例子见下文。

设mask为逻辑值向量,矩阵x的第一列为待查找向量,d为被查询向量(或值),即查找x中与d中指定元素相同的值,并返回逻辑值向量mask。mask是由一系列True和False值构成,True代表找到相同的值,而False代表没找到相同的值。演示如下:

mask= np.in1d(x.values[:,1],d[1],invert=False) ##x为DataFrame型数据,x.values[:,1]表示取第二列值

 x_temp=x[mask]         

 

python中删除list中某指定元素

https://blog.csdn.net/weixin_42814873/article/details/83377431

方法       代码       说明

del   del L[i]    ①根据索引删除;②删除索引范围内的元素;③删除整个列表。del操作没有返回值

pop list.pop(i)   根据索引删除,返回索引位置的元素

remove   list.remove(value)    删除第一个符合条件的元素,注意不是根据索引删除

 

 

python判断目录是否存在,不存在创建一个新的

https://blog.csdn.net/jiangjiang_jian/article/details/80985362

import os

if not os.path.isdir(dir_name):

    os.makedirs(dir_name)

os.mkdir()创建路径中的最后一级目录,而如果之前的目录不存在并且也需要创建的话,就会报错。

os.makedirs()创建多层目录,如果中间目录都不存在的话,会自动创建。

 

判断文件是否存在

https://www.cnblogs.com/jhao/p/7243043.html

if not os.path. exists(dir_name):

work

 

Python变量类型的强制转换

https://blog.csdn.net/yanyangjie/article/details/78329196

 

python路径拼接os.path.join()函数的用法

https://www.cnblogs.com/an-ning0920/p/10037790.html

os.path.join()函数:连接两个或更多的路径名组件

1.如果各组件名首字母不包含’/’,则函数会自动加上

2.如果有一个组件是一个绝对路径,则在它之前的所有组件均会被舍弃

3.如果最后一个组件为空,则生成的路径以一个’/’分隔符结尾

 

Demo1

import os

Path1 = 'home'

Path2 = 'develop'

Path3 = 'code'

Path10 = Path1 + Path2 + Path3

Path20 = os.path.join(Path1,Path2,Path3)

print ('Path10 = ',Path10)

print ('Path20 = ',Path20)

输出

Path10 = homedevelopcode

Path20 = home\develop\code

 

python查看dataframe的头的信息

df.head()
 

python中dataframe的切片

https://blog.csdn.net/yoonhee/article/details/76168253

df.iloc[0,0]

 

Python获取代码运行时间的几种方法

https://blog.csdn.net/asialee_bird/article/details/79673860

方法四:

#在 Unix 系统中,建议使用 time.time(),在 Windows 系统中,建议使用 time.clock()

 

#实现跨平台的精度性可以使用timeit.default_timer()

import timeit

start=timeit.default_timer()

#中间写代码块

end=timeit.default_timer()

print('Running time: %s Seconds'%(end-start))

 

#运行结果

#Running time: 2.31757675399 Seconds

 

python  dataframe转置

df2 = pd.DataFrame(df.values.T, index=df.columns, columns=df.index)

https://blog.csdn.net/a19990412/article/details/90744905

 

python 返回对象的属性

https://www.cnblogs.com/klchang/p/7296058.html

dir() 函数

 dir([object]) 会返回object所有有效的属性列表。

 

python字典排序,按key排序和按value排序---sorted()

>>> d

{'a': 5, 'c': 3, 'b': 4}

 

>>> d.items()

[('a', 5), ('c', 3), ('b', 4)]

 

字典的元素是成键值对出现的,字典的排序可用sorted,用关键字key指定排序依据的值--key或者value

 

按照值排序:

 

#把d.items()所对应的列表的每个元祖的第二个元素(value)传到lambda函数进行排序

>>> s=sorted(d.items(),key=lambda x:x[1])

>>> s

[('c', 3), ('b', 4), ('a', 5)]

 

按照key排序:

 

#把d.items()所对应的列表的每个元祖的第一个元素(key)传到lambda函数进行排序

>>> s=sorted(d.items(),key=lambda x:x[0])

>>> s

[('a', 5), ('b', 4), ('c', 3)]

 

python list 怎么查出一个元素的所有位置

https://zhidao.baidu.com/question/390550100266645085.html?qbl=relate_question_2&word=python%20%B7%B5%BB%D8%D6%B8%B6%A8%D4%AA%CB%D8%CB%F9%D4%DA%B5%C4%CB%F9%D3%D0%CE%BB%D6%C3

def find_all_index(arr,item):

    return [i for i,a in enumerate(arr) if a==item]

    

if __name__=='__main__':

print(find_all_index([1,2,3,2,2],2))

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值