Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python dataframe:对组内的值进行比较_Python_Pandas_Group By_Datatable_Comparison - Fatal编程技术网

Python dataframe:对组内的值进行比较

Python dataframe:对组内的值进行比较,python,pandas,group-by,datatable,comparison,Python,Pandas,Group By,Datatable,Comparison,输入数据: data = {'G1': ['a', 'a', 'a', 'a', 'a', 'b', 'b'], 'G2': ['b', 'b', 'c', 'c', 'd', 'c', 'c'], 'V1': [5, 15, 10, 20, 5, 10, 10], 'V2': [15, 5, 300, 10, 5, 10, 10]} | G1 G2 V1 V2 -- + -- -- -- --- 0 | a b 5 15 1 | a b 15

输入数据:

data = {'G1': ['a', 'a', 'a', 'a', 'a', 'b', 'b'], 'G2': ['b', 'b', 'c', 'c', 'd', 'c', 'c'], 'V1': [5, 15, 10, 20, 5, 10, 10], 'V2': [15, 5, 300, 10, 5, 10, 10]}

   | G1  G2  V1   V2
-- + --  --  --  ---
 0 | a   b    5   15
 1 | a   b   15    5
 2 | a   c   10  300
 3 | a   c   20   10
 4 | a   d    5    5
 5 | b   c   10   10
 6 | b   c   10   10
输出

   | G1  G2  V1   V2  E1  E2
-- + --  --  --  ---  --  --
 0 | a   b    5   15   1   1
 1 | a   b   15    5   1   1
 2 | a   c   10  300   1   0
 3 | a   c   20   10   0   1
 4 | a   d    5    5  NA  NA
 5 | b   c   10   10   1   1
 6 | b   c   10   10   1   1
说明:

如何根据以下条件计算列E1和E2:

只有一行的组应被忽略,并且在E1和E2中没有或没有NA

具有两行的组:

  • 如果V1第一行中的值等于V2第二行中的值,则E1在第一行中应为1(或True),E2在第二行中应为E2

  • 如果V1第二行中的值等于V2第一行中的值,则E1在第二行中应为1(或True),E2在第一行中应为E2

  • 如果值不相等,则相应位置应为0(或假)

如果描述不够清楚,请询问


非常感谢。

从性能角度看,这可能不是最好的方法,但这里有一种使用
np的自定义函数的方法。diag

def func(arr):
    arr = arr.to_numpy()
    if len(arr)<2: return pd.DataFrame([[np.NaN, np.NaN]])
    x, y = np.diag(arr), np.diag(np.fliplr(arr))
    return pd.DataFrame([[np.all(x==x[0]), np.all(y==y[0])],
                         [np.all(y==y[0]), np.all(x==x[0])]])

df[["E1", "E2"]] = df.groupby(["G1","G2"])[["V1","V2"]].apply(func).reset_index(drop=True)

print (df)

  G1 G2  V1   V2   E1   E2
0  a  b   5   15  1.0  1.0
1  a  b  15    5  1.0  1.0
2  a  c  10  300  1.0  0.0
3  a  c  20   10  0.0  1.0
4  a  d   5    5  NaN  NaN
5  b  c  10   10  1.0  1.0
6  b  c  10   10  1.0  1.0
定义函数(arr): arr=arr.to_numpy() if len(arr)