在使用groupby之后,将numpy数组从数据帧传递到一个函数中,该函数在追加回数据帧之前返回numpy数组



如果我有一个包含2个组的数据帧,

--------------------------------------------------
| Date   | Code  | Input  |
--------------------------------------------------
| 1/1/18 | A     | 10     |
--------------------------------------------------
| 1/1/18 | B     | 100    |
--------------------------------------------------
| 1/2/18 | A     | 11     |
--------------------------------------------------
| 1/2/18 | B     | 101    |
--------------------------------------------------

我首先将groupby应用于代码以获得以下内容,

--------------------------------------------------
| Date   | Code  | Input  |
--------------------------------------------------
| 1/1/18 | A     | 10     |
--------------------------------------------------
| 1/2/18 | A     | 11     |
--------------------------------------------------
| 1/1/18 | B     | 100    |
--------------------------------------------------
| 1/2/18 | B     | 101    |
--------------------------------------------------

然后,我根据代码和日期将输入传递给一个函数,该函数只接收并返回一个numpy数组

def func([10, 11]):
returns [20, 25]
def func([100, 101]):
returns [97, 95]

我如何按照原始顺序将numpy数组连接到相应的日期和代码,以获得下面的预期数据帧:

--------------------------------------------------
| Date   | Code  | Input  | Output
--------------------------------------------------
| 1/1/18 | A     | 10     | 20
--------------------------------------------------
| 1/1/18 | B     | 100    | 97
--------------------------------------------------
| 1/2/18 | B     | 11     | 25
--------------------------------------------------
| 1/2/18 | B     | 101    | 95
--------------------------------------------------

您应该能够通过简单的切片来实现这一点。

首先创建用于的数据帧

cols = ['Code', 'Input]
index = pd.date_range('20180101', '20180105', freq='1D')
df1 = pd.DataFrame(data=np.random.randint(0, 10, (5, 2)), index=index, columns=cols)
df2 = pd.DataFrame(data=np.random.randint(0, 10, (5, 2)), index=index, columns=cols)
df3 = pd.concat([df1, df2], axis=0)

确定要传递到函数中的行。注意:这只是一个例子,可以修改为对列而不是索引进行操作。

idx = df3.index==df3.index[0]
>>> df3.loc[idx, :]
Out[21]: 
Code  Input
2018-01-01    A      1
2018-01-01    B      0

然后,您可以从这个切片中获取数据,并将其传递到您的函数中。

>>> df3.loc[idx, 'Input'].values
Out[21]: 
array([1, 0])  # see, it's an array.

您可以通过传递函数的输出,将行添加到df3中

df3.loc[idx, 'Output'] = yourFunction(df3.loc[idx, 'Input'].values)

最新更新