apply()函数在新列

时间:2017-10-03 06:55:47

标签: pandas lambda apply

我是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

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

y DataFrame axis=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 需要$sql = "INSERT INTO tested (itemno, item, quantity) VALUES ('1', '$item', '$quantity')"; 才能$stmt = $conn->prepare("INSERT INTO Users (email, pw) VALUES (?, ?)"); 进行处理:

$stmt->bind_param('ss', $email, $pw);

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

#define your placeholder
a = tf.placeholder(tf.float32, name="asd")

# then, when you need it, fetch if from the graph
graph = tf.get_default_graph()
placeholder = graph.get_tensor_by_name("asd:0")

如果只需要减去列,可以使用更好的解决方案:

<?php 
     $i=0;
     foreach($products as $product){
       echo $product['name'];
       $i++;
       if($i==5){
         break;
       }
     }
?>