[英]How to pass in the f expression column to a function when extending the dataframe in pydatatable?
我正在嘗試生成一些隨機數據並將其保存在數據表中,因此我創建了一個自定義 function 為:
def make_data(nrows):
DT = dt.Frame({'x': 5*np.random.normal(size=nrows)})
DT_EX = DT[:,f[:].extend({'y': 0.01*f['x'] + 0.1*np.random.normal(size=nrows)})]
return DT_EX
在執行此 function 時,它會返回一個 DT:
In [3]: make_data(5)
Out[3]:
| x y
-- + --------- ----------
0 | -0.486592 0.227217
1 | -1.90302 -0.0509506
2 | 4.69407 0.0758279
3 | -7.08778 -0.152139
4 | 0.917043 -0.204939
我想將 np.sin function 添加到 y 列表達式中:
def make_data_version_two(nrows):
DT = dt.Frame({'x': 5*np.random.normal(size=nrows)})
DT_EX = DT[:,f[:].extend({'y': np.sin(f.x) + 0.01*f.x + 0.1*np.random.normal(size=nrows)})]
return DT_EX
在執行此 function 時,它會拋出一個錯誤:
AttributeError Traceback (most recent call last)
<ipython-input-5-81a67037f9f1> in <module>
----> 1 make_data_version_two(5)
<ipython-input-4-e532306680bb> in make_data_version_two(nrows)
3 DT = dt.Frame({'x': 5*np.random.normal(size=nrows)})
4
----> 5 DT_EX = DT[:,f[:].extend({'y': np.sin(f.x) + 0.01*f['x'] + 0.1*np.random.normal(size=nrows)})]
6
7 return DT_EX
AttributeError: 'Expr' object has no attribute 'sin'
我的問題是如何將數據表列傳遞給任何其他函數,如 np.sin(fx) 或 np.round(fx) 等。
我也嘗試過這些變體,但都沒有奏效。
np.sin(f['x'])
np.sin(['x'])
是的,明白了。 我已經查看了數據表數學模塊功能,並創建了一個新的 function 作為
def make_data_version_three(nrows):
DT = dt.Frame({'x': 5*np.random.normal(size=nrows)})
DT_EX = DT[:,f[:].extend({'y': dt.math.sin(f.x) + 0.01*f['x'] + 0.1*np.random.normal(size=nrows)})]
return DT_EX
所以在這里我從數據表中導入了一個數學模塊,我稱之為 sin function 作為
dt.math.sin(f.x)
Output:
In [8]: make_data_version_three(5)
Out[8]:
| x y
-- + --------- ---------
0 | -13.8865 -1.11732
1 | -2.21624 -0.809127
2 | -1.84779 -1.0217
3 | 5.42131 -0.659641
4 | 4.77623 -1.04619
[5 rows x 2 columns]
這里推薦通過datatable的math模塊到go
Numpy 有一些函數可以用來生成隨機數據。 你可以試試這樣的。
import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.rand(10), columns=['x'] )
df['y'] = np.sin(df['x'])
print(df)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.