Pandas 如何为从另一个数据帧创建的变量获取1/0值(根据条件)?(熊猫/努比)

Pandas 如何为从另一个数据帧创建的变量获取1/0值(根据条件)?(熊猫/努比),pandas,Pandas,我有两个数据帧,比如说'df1'和'df2'。 在“df1”中有三个变量:“X”、“Y”、“Z”。 “X”和“Y”表示ID,我对每对(X,Y)进行了计算(无论是哪一对),得到了“Z”变量 在“df2”中有两个变量:“Y”、“W”。 “Y”与“df1”中前面提到的ID相同, “W”是另一个变量(不管怎样) 现在,我想在“df2”中创建(使用pandas)变量,它们是“df1”中的“X”ID, 对于创建的每个变量,如果特定对(X,Y)的“Z”值等于或大于“4”(>=4),并且(&)特定的“W”值等于

我有两个数据帧,比如说'df1'和'df2'。 在“df1”中有三个变量:“X”、“Y”、“Z”。 “X”和“Y”表示ID,我对每对(X,Y)进行了计算(无论是哪一对),得到了“Z”变量

在“df2”中有两个变量:“Y”、“W”。 “Y”与“df1”中前面提到的ID相同, “W”是另一个变量(不管怎样)

现在,我想在“df2”中创建(使用pandas)变量,它们是“df1”中的“X”ID, 对于创建的每个变量,如果特定对(X,Y)的“Z”值等于或大于“4”(>=4),并且(&)特定的“W”值等于或大于“5”(>=5),则要为“df2”中的每一行获取值“1”,否则为“0”

这是数据帧的演示:

df1:

df2:

预期结果(df2):

首先,我们将两个数据帧放在列
Y
上。然后我们将
X
值添加到列中。最后,我们使用
DataFrame.filter
获取正确的列,并使用有条件地应用逻辑来获取列中的
1
0

new = df2.merge(df1,on='Y').pivot_table(index=['Y', 'W'], columns='X', aggfunc='sum').reset_index()
new.columns = [c1 if c2 == '' else str(c2) for c1, c2 in new.columns]

for col in new.filter(regex='\d$').columns:
    new[col] = np.where(new['W'].ge(5) & new[col].ge(4),1,0)
输出

   Y  W  1  2  3
0  a  3  0  0  0
1  a  7  0  0  1
2  b  2  0  0  0
3  b  5  1  1  0
4  b  7  1  1  0
5  c  4  0  0  0
6  c  6  1  0  1
7  c  8  1  0  1
8  c  9  1  0  1

谢谢你,尔凡!它帮助了我。
Y   W   1   2   3
a   7   0   0   1
a   3   0   0   0
b   5   1   1   0
b   7   1   1   0
b   2   0   0   0
c   6   1   0   1
c   9   1   0   1
c   4   0   0   0
c   8   1   0   1
new = df2.merge(df1,on='Y').pivot_table(index=['Y', 'W'], columns='X', aggfunc='sum').reset_index()
new.columns = [c1 if c2 == '' else str(c2) for c1, c2 in new.columns]

for col in new.filter(regex='\d$').columns:
    new[col] = np.where(new['W'].ge(5) & new[col].ge(4),1,0)
   Y  W  1  2  3
0  a  3  0  0  0
1  a  7  0  0  1
2  b  2  0  0  0
3  b  5  1  1  0
4  b  7  1  1  0
5  c  4  0  0  0
6  c  6  1  0  1
7  c  8  1  0  1
8  c  9  1  0  1