简体   繁体   English

创建一个向量,该向量具有根据Pandas DataFrame中的条件从Numpy数组中选择的值

[英]Create a vector with values from a Numpy array selected according to criteria in a Pandas DataFrame

I am working with a pandas df that contains two columns with integers. 我正在使用包含两列带整数的pandas df。 For each data of the df, I would like to select these two integers, use them as [row,column] pairs to extract values from a np.array and create a new np.array with the extracted values. 对于df的每个数据,我想选择这两个整数,将它们用作[row,column]对,以从np.array中提取值,并使用提取的值创建一个新的np.array。

In more detail, my df contains the following entries: 更详细地,我的df包含以下条目:

             State  FutureState
DATE                                                         
1947-10-01       0            0
1948-01-01       0            1
1948-04-01       1            1
1948-07-01       1            1

For each Date , I would like to select the [State,FutureState] pair and extract the corresponding [row,column] item from the following np.array, called P : 对于每个Date ,我想选择[State,FutureState]对,并从以下名为P np.array中提取相应的[row,column]项目:

array([[ 0.7,  0.3],
       [ 0.4,  0.6]])

With these values, I would like to create a new np.array called Transition , which contains of the following values: 使用这些值,我想创建一个名为Transition的新np.array,其中包含以下值:

[P[0,0],P[0,1],P[1,1],P[1,1]] = [0.7, 0.3, 0.6, 0.6] 

The pairs [0,0], [0,1], [1,1] [1,1] used as index for the array P are the values for [State,FutureState] for each date ( 1947-10-01, 1948-01-01 , 1948-04-01, 1948-07-01 ). 用作数组P索引的[0,0], [0,1], [1,1] [1,1] [State,FutureState]对是每个日期[1947-10-01, 1948-01-01,1948-04-01,1948-07-01)。

I already tried to solve my problem in a lot of different ways but to no avail. 我已经尝试过许多不同的方式来解决我的问题,但无济于事。 Can somebody kindly suggest how to successfully create the Transition vector? 有人可以建议如何成功创建Transition向量吗?

How about this? 这个怎么样?

df.apply(lambda x:P[x[0],x[1]], axis=1)

It does what you describe, go row-wise (so apply over axis=1 ) along df and use the entries as index for selecting in P . 它按照您的描述进行操作,沿df逐行(因此适用于axis=1 ),并使用条目作为在P进行选择的索引。

try this: 尝试这个:

p[df.State, df.FutureState]

Here is the full code: 这是完整的代码:

import io
import pandas as pd
import numpy as np

txt = """             State  FutureState                                                        
1947-10-01       0            0
1948-01-01       0            1
1948-04-01       1            1
1948-07-01       1            1"""

df = pd.read_csv(io.BytesIO(txt), delim_whitespace=True)
p = np.array([[ 0.7,  0.3], [ 0.4,  0.6]])
p[df.State, df.FutureState]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM