python - 使用apply()从两​​列创建一个新列

标签 python pandas dataframe apply

我想使用带 Pandas 数据框的apply()创建一列s['C']

我的数据集与此类似:

[在]:

s=pd.DataFrame({'A':['hello', 'good', 'my', 'pandas','wrong'], 
                'B':[['all', 'say', 'hello'],
                     ['good', 'for', 'you'], 
                     ['so','hard'], 
                     ['pandas'],
                     []]})
[Out]: 
    A       B
0   hello   [all, say, hello]
1   good    [good, for, you]
2   my      [so, hard]
3   pandas  [pandas]
4   wrong   []

我需要创建一个as ['C']列,其中如果A列的单词在B列的列表中以及元素在B列的列表中的位置,则每一行的值都是一个依赖于1和0的列表我的输出应该是这样的:
[Out]: 
    A       B                   C
0   hello   [all, say, hello]   [0, 0, 1]
1   good    [good, for, you]    [1, 0, 0]
2   my      [so, hard]          [0, 0]
3   pandas  [pandas]            [1]
4   wrong   []                  [0]


我一直在尝试使用función并申请,但我仍然没有意识到错误在哪里。
[In]:
def func(valueA,listB):
  new_list=[]
  for i in listB:
    if listB[i] == valueA:
      new_list.append(1)
    else:
      new_list.append(0)
  return new_list

s['C']=s.apply( lambda x: func(x.loc[:,'A'], x.loc[:,'B']))

错误是:索引器过多

我还尝试了:
[In]:
list=[]
listC=[]
for i in s['A']:
  for j in s['B'][i]:
     if s['A'][i] == s['B'][i][j]:
        list.append(1)
     else:
        list.append(0)
  listC.append(list)

s['C']=listC

错误是:KeyError:'hello'

有什么建议吗?

最佳答案

如果您使用的是0.25+的 Pandas ,则可以选择explode:

(s.explode('B')
  .assign(C=lambda x: x['A'].eq(x['B']).astype(int))
  .groupby(level=0).agg({'A':'first','B':list,'C':list})
)

输出:
        A                  B          C
0   hello  [all, say, hello]  [0, 0, 1]
1    good   [good, for, you]  [1, 0, 0]
2      my         [so, hard]     [0, 0]
3  pandas           [pandas]        [1]
4   wrong              [nan]        [0]

选项2 :根据您的逻辑,您可以进行列表理解。这应该适用于pandas的任何版本:
s['C'] = [[x==a for x in b] if b else [0] for a,b in zip(s['A'],s['B'])]

输出:
        A                  B                     C
0   hello  [all, say, hello]  [False, False, True]
1    good   [good, for, you]  [True, False, False]
2      my         [so, hard]        [False, False]
3  pandas           [pandas]                [True]
4   wrong                 []                   [0]

关于python - 使用apply()从两​​列创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61733854/

相关文章:

python - TensorFlow:tf.Estimator 模型的输入节点是什么

python - 滚动时间序列数据集的高效构建

python - 如何通过在 Pandas 中联合数组来附加数据帧索引?

python - 如何从字符串的 DataFrame 列中获取唯一单词?

python - celery - AttributeError : 'NoneType' object has no attribute 'delay'

Python - 压缩时的星号

python - 如果索引包含重复值,为什么 pandas 在使用索引时合并速度较慢?

python - 通过列中的标签列表对 Pandas 数据框行进行分组的有效方法

python - 使用 python pandas 如何进行一些分析以识别有效的手机号码

python - 如何配置 uWSGI 以便使用 pdb 进行调试(--honour-stdin 配置问题)