Nac*_*gue 10 python apply dataframe pandas
我想s['C']
使用 apply() 和 Pandas DataFrame创建一列。
我的数据集类似于:
[在]:
s=pd.DataFrame({'A':['hello', 'good', 'my', 'pandas','wrong'],
'B':[['all', 'say', 'hello'],
['good', 'for', 'you'],
['so','hard'],
['pandas'],
[]]})
Run Code Online (Sandbox Code Playgroud)
[Out]:
A B
0 hello [all, say, hello]
1 good [good, for, you]
2 my [so, hard]
3 pandas [pandas]
4 wrong []
Run Code Online (Sandbox Code Playgroud)
我需要创建 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]
Run Code Online (Sandbox Code Playgroud)
我一直在尝试使用功能并申请,但我仍然没有意识到错误在哪里。
[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']))
Run Code Online (Sandbox Code Playgroud)
错误是:索引器太多
我也尝试过:
[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
Run Code Online (Sandbox Code Playgroud)
错误是: KeyError: 'hello'
有什么建议吗?
如果您正在使用 pandas 0.25+,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})
)
Run Code Online (Sandbox Code Playgroud)
输出:
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]
Run Code Online (Sandbox Code Playgroud)
选项 2:根据您的逻辑,您可以进行列表理解。这应该适用于任何版本的pandas
:
s['C'] = [[x==a for x in b] if b else [0] for a,b in zip(s['A'],s['B'])]
Run Code Online (Sandbox Code Playgroud)
输出:
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]
Run Code Online (Sandbox Code Playgroud)
随着apply
将是
s['c'] = s.apply(lambda x: [int(x.A == i) for i in x.B], axis=1)
s
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 [] []
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
427 次 |
最近记录: |