【问题标题】:ValueError: The truth value of a Series is ambiguous.in a for loopValueError: Series 的真值不明确。在 for 循环中
【发布时间】:2020-01-27 14:53:51
【问题描述】:

我正在尝试使用 for 循环遍历 DataFrame,但出现此错误:

"ValueError: Series 的真值不明确。"

我的数据框是:

我想遍历“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')

提前致谢。

【问题讨论】:

    标签: python pandas for-loop


    【解决方案1】:

    第一个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)
    

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 2019-12-19
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 2023-01-08
      • 2020-03-05
      • 2020-09-28
      • 1970-01-01
      相关资源
      最近更新 更多