【问题标题】:apply() function to generate new value in a new columnapply() 函数在新列中生成新值
【发布时间】:2017-10-03 06:55:46
【问题描述】:

我是 python 3 和 pandas 的新手。我尝试将新列添加到数据框中,其中值是两个现有列之间的差异。 我当前的代码是:

import pandas as pd
import io
from io import StringIO
x="""a,b,c
1,2,3
4,5,6
7,8,9"""

with StringIO(x) as df:
    new=pd.read_csv(df)

print (new)

y=new.copy()

y.loc[:,"d"]=0

# My lambda function is completely wrong, but I don't know how to make it right.

y["d"]=y["d"].apply(lambda x:y["a"]-y["b"], axis=1)

想要的输出是

a b c d

1 2 3 -1

4 5 6 -1

7 8 9 -1

有人知道如何让我的代码工作吗?

感谢您的帮助。

【问题讨论】:

    标签: pandas lambda apply


    【解决方案1】:

    您需要 y 仅用于 DataFrame 用于 DataFrame.applyaxis=1 用于按行处理:

    y["d"]= y.apply(lambda x:x["a"]-x["b"], axis=1)
    

    为了更好的调试,可以创建自定义函数:

    def f(x):
        print (x)
        a = x["a"]-x["b"]
        return a
    
    y["d"]= y.apply(f, axis=1)
    
    a    1
    b    2
    c    3
    Name: 0, dtype: int64
    a    4
    b    5
    c    6
    Name: 1, dtype: int64
    a    7
    b    8
    c    9
    Name: 2, dtype: int64
    

    如果只需要减去列,则更好的解决方案:

    y["d"] = y["a"] - y["b"]
    
    print (y)
       a  b  c  d
    0  1  2  3 -1
    1  4  5  6 -1
    2  7  8  9 -1
    

    【讨论】:

    • 非常感谢您的回复。真的行。请问在这种情况下x代表什么?是指y的每一行吗?
    • 没错,就是每一行,因为axis=1。如果axis=0,就是每一列。
    猜你喜欢
    • 2022-01-24
    • 2013-01-14
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多