我试图在python中迭代一个数据帧,在if语句中,我引用了碰巧是一个系列的两列。运行代码时,出现以下错误:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
数据:
取自@CypherX提供的溶液。你知道吗
template = ['some', 'abra', 'cadabra', 'juju', 'detail page', 'lulu', 'boo', 'honolulu', 'detail page']
prev = ['home', 'abra', 'cacobra', 'juju', 'detail page', 'lulu', 'booboo', 'picabo', 'detail here']
df = pd.DataFrame({'Template': template, 'Prev': prev})
Template Prev
0 some home
1 abra abra
2 cadabra cacobra
3 juju juju
4 detail page detail page
5 lulu lulu
6 boo booboo
7 honolulu picabo
8 detail page detail here
我的代码如下:
for row in s:
if (s['Template']=='detail page') and (s['Template']==s['Prev']):
s['Swipe']=1
else:
s['Swipe']=0
其中s
是我的数据帧。你知道吗
我能做些什么来解决这个问题?有什么想法吗?你知道吗
我能想到的两个快速方法:
因为,你没有提供任何可复制的问题数据,我自己做了,这里是解决办法。你知道吗
短期解决方案
详细解决方案
将条件求值为
boolean
,由于要为True
赋值1,为False
赋值0,只需将boolean
转换为int
即可。你知道吗输出:
你的解决方案有什么问题?你知道吗
s
(注意:通常s
用于series,df
用于dataframe),并返回列名。因此row
实际上不会返回数据帧的行。你知道吗row
。你知道吗我将用dataframe
df
打印输出以表明我的观点:输出:
您可以尝试使用
np.where
来设置s['Swipe']
的值:相关问题 更多 >
编程相关推荐