ValueError:序列的真值不明确。在for循环中

2024-05-23 18:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用for循环遍历数据帧,但遇到以下错误:

“ValueError:序列的真值不明确。”

我的数据帧是: Dataframe

我想通过“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')

提前谢谢


Tags: 数据forindexperformanceyahooreplacestrtaboola
1条回答
网友
1楼 · 发布于 2024-05-23 18:17:32

首先iterrows是pandas中最慢的迭代解决方案之一,最好避免它,检查this answer by pandas developer Jeff

因此,您可以创建用于替换的词典,使用^{}按掩码筛选行,并使用^{}

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)

相关问题 更多 >