【发布时间】:2020-08-27 05:44:23
【问题描述】:
我想使用带有 Pandas DataFrame 的 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'] 列,其中每行的值是一个列表,其中 1 和 0 取决于 A 列的单词是否在 B 列的列表中以及元素在列表中的位置B 列的。我的输出应该是这样的:
[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]
我一直在尝试使用功能并申请,但我仍然没有意识到错误在哪里。
[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'
有什么建议吗?
【问题讨论】:
-
列表是否必要?您可以使用 MultiIndex 进行组织,其中第一级是您的原始索引,第二级是您的列表索引。然后所有这些操作变得更加高效。
-
@ALollz,你说的很有趣。你有例子吗?我的 github 用户名是 Ignacio-Ibarra,谢谢
标签: python pandas dataframe apply