我想使用带 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/