Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.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 检查一列的值是否存在于另一列中,将一个值放入另一列中_Python_Pandas - Fatal编程技术网

Python 检查一列的值是否存在于另一列中,将一个值放入另一列中

Python 检查一列的值是否存在于另一列中,将一个值放入另一列中,python,pandas,Python,Pandas,假设我有一个如下所示的数据帧: A B C D E a1 b1 c1 d1 e1 a2 a1 c2 d2 e2 a3 a1 a2 d3 e3 a4 a1 a2 a3 e4 如果在其他列中找到值,我想创建一个具有预定义值的新列。 大概是这样的: A B C D E F a1 b1 c1 d1 e1 NA a2 a1 c2 d2 e2 in_B a3 a1 a2 d3 e3 in_B, in_C a4 a1 a2 a3 e4 in_B, in_C, in_D B中的和C中的可以是其他选择字符串。

假设我有一个如下所示的数据帧:

A B C D E
a1 b1 c1 d1 e1
a2 a1 c2 d2 e2
a3 a1 a2 d3 e3
a4 a1 a2 a3 e4
如果在其他列中找到值,我想创建一个具有预定义值的新列。 大概是这样的:

A B C D E F
a1 b1 c1 d1 e1 NA
a2 a1 c2 d2 e2 in_B
a3 a1 a2 d3 e3 in_B, in_C
a4 a1 a2 a3 e4 in_B, in_C, in_D
B中的
和C中的
可以是其他选择字符串。如果值出现在多个列中,则
F
的值将是多个。例如,F列的第3行和第4行(第3行有两个值,第4行有三个值)。到目前为止,我已经尝试了以下方法:

DF.F=np.where(DF.A.isin(DF.B), DF.A,'in_B')
但它并没有给出预期的结果。任何帮助

步骤:
  • 堆栈
    数据帧
  • 检查是否存在重复的
  • 取消堆叠
    以恢复相同的结构
  • 使用
    dot
    获得所需结果
  • 输出:
    根据您给出的输出,选择的字符串是什么?如果A出现在B中,字符串可以是“X”,如果C中出现,字符串可以是“Y”,如果D中出现,字符串可以是“Z”,因此,如果B和C中出现,字符串可以是“X,Y”,如果B,C和D中出现,字符串可以是“X,Y,Z”。不清楚,请参考您的首选输出,并向我们解释,例如,在新列中,如果A的值存在于多个列中,则该值将是多个。在新列中,第4行如何变为
    a4 a1 a2 a3 e4 in_B,in_C,in_D
    。在第4行中,A的值存在于B、C和D中。现在有意义了吗?
    df['new_col'] = df.stack().duplicated().unstack().dot(
        'In ' + k.columns + ',').str.strip(',')
    
        A   B   C   D   E         new_col
    0  a1  b1  c1  d1  e1                
    1  a2  a1  c2  d2  e2            In B
    2  a3  a1  a2  d3  e3       In B,In C
    3  a4  a1  a2  a3  e4  In B,In C,In D