Numpy 的 fromfunction(~)
方法使用初始化每個單元格值的函數構造 Numpy 數組。
參數
1. function
| callable
一個函數,它接受行和列索引,並返回該單元格的值。
2. shape
| sequence
共 int
所得數組的所需形狀。
3. dtype
| string
或 type
| optional
結果數組所需的數據類型。默認情況下,dtype=Float
。
返回值
一個 Numpy 數組。
例子
使用匿名函數
要創建一個 2 x 2 Numpy 數組,其中對角線設置為 True,其他位置設置為 False:
np.fromfunction(lambda i,j: i==j, (2,2))
array([[ True, False],
[False, True]])
在這裏,該函數接受行索引和列索引作為參數。
使用顯式函數
在這裏,我們定義了一個名為 foo 的顯式函數:
def foo(i, j):
return i + j
我們可以像這樣使用fromfunction(~)
方法:
np.fromfunction(foo, (3,3))
array([[0., 1., 2.],
[1., 2., 3.],
[2., 3., 4.]])
相關用法
- Python Django fromfile用法及代碼示例
- Python dict fromkeys()用法及代碼示例
- Python NumPy frombuffer方法用法及代碼示例
- Python NumPy fromstring方法用法及代碼示例
- Python Django from_queryset用法及代碼示例
- Python Django fromstr用法及代碼示例
- Python NumPy fromiter方法用法及代碼示例
- Python frozenset()用法及代碼示例
- Python frexp()用法及代碼示例
- Python fractions.Fraction用法及代碼示例
- Python fractions.Fraction.limit_denominator用法及代碼示例
- Python fractions.Fraction.__floor__用法及代碼示例
- Python NumPy fliplr方法用法及代碼示例
- Python BeautifulSoup find_next方法用法及代碼示例
- Python functools.wraps用法及代碼示例
- Python NumPy floor方法用法及代碼示例
- Python functools.singledispatchmethod用法及代碼示例
- Python float轉exponential用法及代碼示例
- Python calendar firstweekday()用法及代碼示例
- Python NumPy full方法用法及代碼示例
- Python NumPy flatten方法用法及代碼示例
- Python float.is_integer用法及代碼示例
- Python Django format_lazy用法及代碼示例
- Python format()用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 NumPy | fromfunction method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。