【问题标题】:Assign values to multiple columns using DataFrame.assign()使用 DataFrame.assign() 为多个列赋值
【发布时间】:2023-01-19 17:21:40
【问题描述】:

我有一个存储在 pandas 数据框df 中的字符串列表,列名是文本(即df['text'])。 我有一个函数f(text: str) -> (int, int, int)。 现在,我想做以下事情。

df['a'], df['b'], df['c'] = df['text'].apply(f)

如何使用函数的三个返回值创建三列?

上面的代码给出了错误

ValueError: too many values to unpack (expected 3)

我试过了

df['a', 'b', 'c'] = df['text'].apply(f)

但我得到一列名称为'a', 'b', 'c'

注意:

  1. SO 中有一个similar question,但是当我从那里使用以下解决方案时,我再次遇到错误。
    df[['a', 'b', 'c']] = df['text'].apply(f, axis=1, result_type='expand')
    

    错误是

    f() got an unexpected keyword argument 'axis'
    f() got an unexpected keyword argument 'result_type' #(once I remove the axis=1 parameter)
    
    1. 注意df还有其他列

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    对我来说,您的解决方案有效。但是需要测试元组中是否正确返回 3 个值。

    这是替代方案:

    df = pd.DataFrame({'text':[1,2,3]})
    
    def f(x):
        return((x,x+1,x-5))
    
    df[['a', 'b', 'c']] = pd.DataFrame(df['text'].apply(f).tolist(), index=df.index)
    print (df)
       text  a  b  c
    0     1  1  2 -4
    1     2  2  3 -3
    2     3  3  4 -2
    

    【讨论】:

    • 它有效,但是 1. 我收到 following warning。 2. 你能否概述一下正在发生的事情,tolist()index=df.index 做了什么。
    • @berinaniesh - 第一个警告 - 在我的解决方案之前我没有过滤?喜欢df = df[df['col'] > 10]?如果是,为避免它使用 copy like df = df[df['col'] > 10].copy()
    • @berinaniesh - 对于元组列表,使用tolist()函数,然后对于具有相同索引值的DataFrame,传递df.index。如果原始数据帧具有不同的索引,则这是必要的。
    猜你喜欢
    • 2020-07-13
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多