python - for循环中出现ValueError : The truth value of a Series is ambiguous.

标签 python pandas for-loop

我正在尝试使用 for 循环迭代 DataFrame,但收到此错误:

“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')

提前致谢。

最佳答案

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

相关文章:

python - Pandas 根据多个条件过滤行

python - 如何制作一个显示日期列范围的标题?

python - 如何从其他两列之间的列中获取数据框的行?

python - for 或 while 循环做 n 次

java - 如何在循环中声明标签?

python - SQLAlchemy 中的一对多关系

python - 在套接字上接收到一些输入后创建顶级

python - 如何从指定值的字典中获取所有键?

python - 使用 spaCy 提取两个连续的名词

for-loop - 在 Maxima 中,我该如何解这个方程?