1. 引索
(1)dataframe
df[条件].index # 引索值
df[df.str.contains(正则表达式)].index # df.str.contains(正则表达式) 为bool值
(2) list
list = ['Mike', 'male', '24']
for index, value in enumerate(list):
print("索引:" + str(index), ", 值:" + value)
'''
'result':
索引:0 , 值:Mike
索引:1 , 值:male
索引:2 , 值:24
'''
2. 异常处理
(1)try/except
def main():
a=3/1
print(a)
try:
main()
except ZeroDivisionError:
print("error")
else:
print(main())
finally:
print("always do this")
(2)raise
raise NameError('自己定义解释文本')
运行到raise时必抛出异常
(3)assert
assert 判断条件
判断条件为True时,继续运行;False,抛出异常
3. io流
(1)获取当前目录
os.getcwd()
(2)获取上级目录
os.path.dirname(os.getcwd())
(3)pandas.read_csv() 报错 OSError: Initializing from file failed
train_data_org = pd.read_csv(train_path,engine='python')
(4)import 自定义py文件
import sys
sys.path.append(r"路径")
from simulate_utils import *
4.时间
datetime
(1)文本转日期格式:strptime
datetime.strptime(‘2021-5-10 9:30:45’, ‘%Y-%m-%d %H:%M:%S’)
(2)日期格式转文本:strftime
datetime.strftime(datetime.now(), “%Y-%m-%d %H:%M”)
附
(1)异常类型 (参考[1])
名称 | 描述 |
---|---|
BaseError | 所有异常的基类 |
SystemExit | 解释器请求退出 |
KeyBoardInterrupt | 用户中断执行(ctrl+c) |
Exception | 常规错误的基类 |
AssertionError | 断句错误,当assert关键字后面的条件为假时,程序就会抛出 |
FileNotFoundError | 文件不存在 |
AttributeError | 属性错误,对象属性不存在的时候 |
IndexError | 索引错误,索引超出范围 |
KeyError | 在字典中查找一个不存在的关键字 |
NameError | 尝试访问一个不存在的变量 |
SyntaxError | 语法错误 |
TypeError | 类型错误,不同类型间的无效操作,1+“1” |
ZeroDivisionError | 除0错误,分母为0 |
EOFError | 没有内建输入,到达EOF标记 |
IOError | 输入/输出操作失败 |
OSError | 操作系统错误 |
WindowsError | 系统调用失败 |
RuntimeError | 一般的运行时错误 |
IndentationError | 缩进错误 |
SystemError | 一般的解释器错误 |
TabError | Tab和空格混用 |
Warning | 所有警告的基类 |
参考博文
[1]Python的异常处理机制
[2]Python3 assert(断言)
[3]python里读取文件路径上一级路径及文件的方法
[4]pandas.read_csv() 报错 OSError: Initializing from file failed,报错原因分析和解决方法
[5]Python中datetime.strptime()和strftime()的应用