我正在尝试使用 for 循环迭代 DataFrame,但收到此错误:
“ValueError:系列的真值不明确。”
我想迭代“Plataforma”和“Soporte”来替换“Soporte”值。 我正在使用这个:
for index, row in informe.iterrows():
if informe.loc[index, 'Plataforma'] == 'Taboola':
informe['Soporte'].str.replace('performance-prospecting_tconvergentes', 'Prospecting_Taboola_tconvergentes')
informe['Soporte'].str.replace('performance-prospecting_tmoviles', 'Prospecting_Taboola_tmoviles')
informe['Soporte'].str.replace('performance-prospecting', 'Prospecting_Taboola')
elif informe.loc[index, 'Plataforma'] == 'Yahoo':
informe['Soporte'].str.replace('performance-prospecting_tconvergentes', 'Prospecting_Yahoo_tconvergentes')
informe['Soporte'].str.replace('performance-prospecting_tmoviles', 'Prospecting_Yahoo_tmoviles')
informe['Soporte'].str.replace('performance-prospecting', 'Prospecting_Yahoo')
提前致谢。
最佳答案
第一个 iterrows
是 pandas 中最慢的迭代解决方案之一,最好避免它,请检查 this answer by pandas developer Jeff .
因此,您可以创建用于替换的字典,使用 DataFrame.loc
按掩码过滤行并使用Series.replace
:
d1= {'performance-prospecting_tconvergentes': 'Prospecting_Taboola_tconvergentes',
'performance-prospecting_tmoviles': 'Prospecting_Taboola_tmoviles',
'performance-prospecting': 'Prospecting_Taboola'}
d2 = {'performance-prospecting_tconvergentes': 'Prospecting_Yahoo_tconvergentes',
'performance-prospecting_tmoviles': 'Prospecting_Yahoo_tmoviles',
'performance-prospecting':'Prospecting_Yahoo'}
m1 = informe['Plataforma'] == 'Taboola'
m2 = informe['Plataforma'] == 'Yahoo'
informe.loc[m1, 'Soporte'] = informe.loc[m1, 'Soporte'].replace(d1)
informe.loc[m2, 'Soporte'] = informe.loc[m2, 'Soporte'].replace(d2)
关于python - for循环中出现ValueError : The truth value of a Series is ambiguous.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59933526/