Kaggle课程官方链接:Working with External Libraries
本专栏旨在Kaggle官方课程的汉化,让大家更方便地看懂。
Working with External Libraries
导入、运算符重载和进入外部库世界的生存技巧
在本教程中,您将学习Python中的导入,获得一些使用不熟悉的库(以及它们返回的对象)的技巧,并深入了解运算符重载。
Imports
到目前为止,我们已经讨论了语言内置的类型和函数。
但是Python最好的一点(特别是如果你是一名数据科学家)是为它编写了大量高质量的自定义库。
其中一些库位于“标准库”中,这意味着您可以在运行Python的任何地方找到它们。其他库可以很容易地添加,即使它们并不总是与Python一起提供。
无论哪种方式,我们都将通过导入访问此代码。
我们将从标准库导入数学来开始我们的示例。
import math
print("It's math! It has type {}".format(type(math)))
It's math! It has type <class 'module'>
数学是一个模块。模块只是由其他人定义的变量(如果你愿意,可以称之为命名空间)的集合。我们可以使用内置函数dir()查看数学中的所有名称。
print(dir(math))
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
我们可以使用点语法访问这些变量。其中一些引用了简单的值,比如math.pi:
print("pi to 4 significant digits = {:.4}".format(math.pi))
pi to 4 significant digits = 3.142
但我们在模块中发现的大部分都是函数,比如math.log:
math.log(32, 2)
5.0
当然,如果我们不知道math.log的作用,我们可以对它调用help():
help(math.log)
Help on built-in function log in module math:
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
我们也可以对模块本身调用help()。这将为我们提供模块中所有函数和值的组合文档(以及模块的高级描述)。运行结果太多,这里不演示了,自己可以多多尝试。
help(math)
Other import syntax
如果我们知道我们将经常使用数学中的函数,我们可以在较短的别名下导入它以节省一些打字时间(尽管在这种情况下“math”已经很短了)。
import math as mt
mt.pi
3

最低0.47元/天 解锁文章
1036

被折叠的 条评论
为什么被折叠?



