> 文章列表 > Python学习笔记202302

Python学习笔记202302

Python学习笔记202302

1、numpy.empty
作用:根据给定的维度和数值类型返回一个新的数组,其元素不进行初始化。
用法:numpy.empty(shape, dtype=float, order=‘C’)

2、logging.debug
作用:Python 的日志记录工具,这个模块为应用与库实现了灵活的事件日志系统的函数与类。
Python学习笔记202302
图片来源:
https://docs.python.org/zh-cn/3/library/logging.html
https://blog.csdn.net/weixin_41724044/article/details/81784974

3、assert函数
https://docs.python.org/3/reference/simple_stmts.html#assert
作用:Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。断言可以在条件不满足程序运行的情况下直接返回错误,而不必等待程序运行后出现崩溃的情况
用法:assert expressionassert expression [, arguments]
如果expression是True,那么什么反应都没有。但是如果expression是False,那么会报错AssertionError。

4、np.where函数
(1)np.where(condition):返回值是满足condition的元素的下标;
(2)np.where(condition, x, y):返回值是一个和condition的shape相同的numpy 数组,当满足条件condition时,返回值中的元素从x中取,否则从y中取。

5、python读取shapefile文件

import shapefile
sh=shapefile.Reader('./shp/shapefile_file.shp')
shapefile_records=sh.records()#records,according to arcgis fileds

6、python 中两个//表示:地板除,即先做除法(/),然后向下取整(floor)。

7、python netcdf: making a copy of all variables and attributes but one
解决方法:https://stackoverflow.com/questions/15141563/python-netcdf-making-a-copy-of-all-variables-and-attributes-but-one
代码:

import netCDF4 as nc
toexclude = ['ExcludeVar1', 'ExcludeVar2']with netCDF4.Dataset("in.nc") as src, netCDF4.Dataset("out.nc", "w") as dst:# copy global attributes all at once via dictionarydst.setncatts(src.__dict__)# copy dimensionsfor name, dimension in src.dimensions.items():dst.createDimension(name, (len(dimension) if not dimension.isunlimited() else None))# copy all file data except for the excludedfor name, variable in src.variables.items():if name not in toexclude:x = dst.createVariable(name, variable.datatype, variable.dimensions)dst[name][:] = src[name][:]# copy variable attributes all at once via dictionarydst[name].setncatts(src[name].__dict__)

或者(测试可用):

import netCDF4 as nc
import numpy as np
toexclude = ["TO_REMOVE"]
with nc.Dataset("orig.nc") as src, nc.Dataset("filtered.nc", "w") as dst:# copy attributesfor name in src.ncattrs():dst.setncattr(name, src.getncattr(name))# copy dimensionsfor name, dimension in src.dimensions.iteritems():dst.createDimension(name, (len(dimension) if not dimension.isunlimited else None))# copy all file data except for the excludedfor name, variable in src.variables.iteritems():if name not in toexclude:x = dst.createVariable(name, variable.datatype, variable.dimensions)dst.variables[name][:] = src.variables[name][:]

代码来源:https://stackoverflow.com/questions/15141563/python-netcdf-making-a-copy-of-all-variables-and-attributes-but-one
Python setattr() 函数:
功能:setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
用法:setattr(object, name, value)

8、dataframe and series
series 对象转字符串:df[['station']] = pd.Series(df['station'], dtype="string")
筛选满足条件的行:df_new = df.loc[df['station'].str.contains('姓名')]

Python将循环过程中产生的dataframe,按行合并,最终输出一个csv文件:

merge_result = []
for file in os.listdir(csv_path):df = pd.read_csv(os.path.join(csv_path,file),header = None,names=['field1','field2'])merge_result .append(df_new)
df_all = pd.concat(merge_result , axis=0)

9、dataframe输出csv文件,中文出现乱码问题
https://blog.csdn.net/chenpe32cp/article/details/82150074

df.to_csv("result.csv",encoding="utf_8_sig")