比较两列中的值,并在pandas的第三列中输出结果

2024-05-01 21:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据如下所示,我试图用给定的值创建列输出。在

      a_id b_received c_consumed
  0    sam       soap        oil
  1    sam        oil        NaN
  2    sam      brush       soap
  3  harry        oil      shoes
  4  harry      shoes        oil
  5  alice       beer       eggs
  6  alice      brush      brush
  7  alice       eggs        NaN

生成数据集的代码是

^{pr2}$

我想要一个名为Output的新列,它看起来像这样

      a_id b_received c_consumed   output
  0    sam       soap        oil   1
  1    sam        oil        NaN   1
  2    sam      brush       soap   0
  3  harry        oil      shoes   1
  4  harry      shoes        oil   1
  5  alice       beer       eggs   0
  6  alice      brush      brush   1 
  7  alice       eggs        NaN   1 

因此,搜索是如果sam收到了soap、oil和brush,请在“consumped”列中查找他消费的产品的值,因此如果消耗了soap,那么输出将为1,但是由于没有消耗brush,所以输出为0。在

同样对于哈利来说,他收到了油和鞋,然后在消耗栏中寻找油和鞋,如果消耗了油,输出是1。在

更清楚地说,输出值对应于第一列(已接收),取决于第二列(已消耗)中的值。在

我试着用这个代码

   a=[]
   for i in range(len(df.b_received)):
         if any(df.c_consumed == df.b_received[i] ):
              a.append(1)
         else:
              a.append(0)

   df['output']=a

这给了我输出

       a_id b_received c_consumed  output
  0    sam       soap        oil       1
  1    sam        oil        NaN       1
  2    sam      brush       soap       1
  3  harry        oil      shoes       1
  4  harry      shoes        oil       1
  5  alice       beer       eggs       0
  6  alice      brush      brush       1
  7  alice       eggs        NaN       1

问题是,由于sam没有使用画笔,所以输出应该是0,但是输出是1,因为画笔是由另一个人(alice)使用的。我要确保这不会发生。产出需要具体到每个人的消费。在

我知道这是令人困惑的,所以如果我没有说清楚,请一定要问,我会回答你的意见。在


Tags: iddfsamnansoapeggsoilalice
2条回答

这应该是可行的,尽管理想的方法是JaminSore给出的方法

df['output'] = 0

ctr = 0

for names in df['a_id'].unique():
    for n, row in df.loc[df.a_id == names].iterrows():
        if row['b_received'] in df.loc[df.a_id == names]['c_consumed'].values:
            df.ix[ctr:]['output']=1
            ctr+=1
        else:
            df.ix[ctr:]['output']=0
            ctr+=1

数据帧现在正在

^{pr2}$

键是pandas.Series.isin(),它检查传递给pandas.Series.isin()的对象中调用pandas.Series中每个元素的成员身份。您要使用c_consumed检查b_received中每个元素的成员身份,但只能在由a_id定义的每个组内。当将groupbyapply一起使用时,pandas将通过分组变量及其原始索引来索引对象。在您的例子中,您不需要索引中的分组变量,所以可以使用drop=True将索引重置回原来的状态。在

df['output'] = (df.groupby('a_id')
               .apply(lambda x : x['b_received'].isin(x['c_consumed']).astype('i4'))
               .reset_index(level='a_id', drop=True))

你的DataFrame现在是。。。在

^{pr2}$

请查看有关使用pandas的split-apply-combine的文档,以获得更彻底的解释。在

相关问题 更多 >