【问题标题】:How to call pandas dataframe apply function to return two variables如何调用熊猫数据框应用函数返回两个变量
【发布时间】:2021-09-20 19:45:04
【问题描述】:

我想调用pandas dataframe apply()函数返回两个变量

例如:

print(word_list)
['abc', 'lmn', ]

def is_related_content(x):
    for y in word_list:
        if y in x:
            return x, y
    return '', ''

print(df.head())
    str1        
    abcdef      
    hijklmn     
    asddada    
    
# call apply() function like this
df['string'], df['substring'] = df['str1'].apply(lambda x: is_related_content(x))

# it should be like this
print(df.head())
    str1        string      substring
    abcdef      abcdef      abc
    hijklmn     hijklmn     lmn
    asddada     None        None               

但我收到如下错误消息:

news_df['merge_' + col], news_df[col] = news_df['content'].fillna("").apply(lambda x: is_related_content(x))
ValueError:要解压的值太多(预期为 2)

谁能帮帮我?
提前致谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    函数is_related_content 为应用该函数的列中的每个值返回元组,因此尝试像这样分配值是行不通的,因为每一行都有值的元组。一种解决方案是将pd.Series 应用于每个单独的元组,并将它们分配回数据框的列列表; 想法是将元组拆分为多列(类似于 explode 将值拆分为多行):

    >>> df[['string', 'substring']] = df['str1'].apply(is_related_content).apply(pd.Series)
    >>> df
          str1   string substring
    0   abcdef   abcdef       abc
    1  hijklmn  hijklmn       lmn
    2  asddada  
    

    【讨论】:

      【解决方案2】:

      您需要一个 Series 元组才能使 unpacking 语法起作用。但是apply 方法返回的是一系列元组。您可以在apply 之后使用.str 访问器,以便将结果解压缩为元组:

      更新:

      s = df['str1'].apply(lambda x: is_related_content(x))
      df['string'], df['substring'] = s.str[0], s.str[1]
      df
      #      str1   string substring
      #0   abcdef   abcdef       abc
      #1  hijklmn  hijklmn       lmn
      #2  asddada                   
      

      df['string'], df['substring'] = df['str1'].apply(lambda x: is_related_content(x)).str
      
      df
      #      str1   string substring
      #0   abcdef   abcdef       abc
      #1  hijklmn  hijklmn       lmn
      #2  asddada                   
      

      【讨论】:

      • 但它给出了这样的警告,FutureWarning: Columnar iteration over characters will be deprecated in future releases. df['string'], df['substring'] = df['str1'].apply(lambda x: is_related_content(x)).str 。我之前搜索过Columnar iteration,但没有找到与之相关的内容。如果不介意,你能帮我解释一下吗?
      猜你喜欢
      • 2014-07-04
      • 2019-12-10
      • 1970-01-01
      • 2022-01-21
      • 2018-05-13
      • 2021-12-30
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多