“In”迭代问题
问题描述:
这是超基本的,但我可以用一只手。“In”迭代问题
我有一个数据帧,看起来像这样:
name yes no
0 'a' ('b',)
1 'b' ('a',)
2 'c' ('a', 'b')
我试图将比分这样的数据:
def score(x):
if x[0] in x[1] == True:
return 1
if x[0] in x[2] == True:
return 0
else:
[]
sh['label']= sh.apply(score, axis=1)
在第二个if语句,但不是第一,我得到这个错误
TypeError: ("argument of type 'float' is not iterable", 'occurred at index 1')
它似乎是没有与一个项目的元组的问题,但不喜欢与两个元组。
我该如何解决?
答
问题是与NaN
,所以一个可能的解决方案是fillna
某些值未在柱name
第一:
#if need select by position use iloc
def score(x):
print (x)
if x.iloc[0] in x.iloc[1]:
return 1
elif x.iloc[0] in x.iloc[2]:
return 0
sh['label']= sh.fillna('tmp').apply(score, axis=1)
print(sh)
#if need select by column name
def score(x):
#print (x)
if x['name'] in x['yes']:
return 1
elif x['name'] in x['no']:
return 0
sh['label']= sh.fillna('tmp').apply(score, axis=1)
print(sh)
样品:
sh = pd.DataFrame({
'name': ['b','b','b'],
'yes': [('b',),('a',),np.nan],
'no':[np.nan, np.nan, ('a','b')]
})
print(sh)
name no yes
0 b NaN (b,)
1 b NaN (a,)
2 b (a, b) NaN
def score(x):
#print (x)
if x['name'] in x['yes']:
return 1
elif x['name'] in x['no']:
return 0
sh['label']= sh.fillna('tmp').apply(score, axis=1)
print(sh)
name no yes label
0 b NaN (b,) 1.0
1 b NaN (a,) NaN
2 b (a, b) NaN 0.0
但随着代码问题以上是如果值在列yes
和0中。一个可能的解决方案是创建2
新列与boolean
True
和False
,然后转换为int
(1
,0
)由astype
:
sh = pd.DataFrame({
'name': ['b','b','b'],
'yes': [('b',),('a',),np.nan],
'no':[np.nan, ('b',), ('a','b')]
})
print(sh)
name no yes
0 b NaN (b,)
1 b (b,) (a,)
2 b (a, b) NaN
sh['label-yes']= sh.fillna('tmp').apply(lambda x: x['name'] in x['yes'], axis=1)
sh['label-no']= sh.fillna('tmp').apply(lambda x: x['name'] in x['no'], axis=1)
sh[['label-yes', 'label-no']] = sh[['label-yes', 'label-no']].astype(int)
print(sh)
name no yes label-yes label-no
0 b NaN (b,) 1 0
1 b (b,) (a,) 0 1
2 b (a, b) NaN 0 1
什么是预期的输出? – Zero
为什么'== True'?... – TigerhawkT3
'x'可能不包含您的期望。把'print(x [2])放在第二个'if'之前。 – Barmar