pandas -使用apply()时,“系列"对象没有属性"colNames" [英] Pandas - 'Series' object has no attribute 'colNames' when using apply()

查看:91
本文介绍了 pandas -使用apply()时,“系列"对象没有属性"colNames"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用lambda函数进行逐行计算.例如创建一些数据框

I need to use a lambda function to do a row by row computation. For example create some dataframe

import pandas as pd
import numpy as np

def myfunc(x, y):
    return x + y

colNames = ['A', 'B']
data = np.array([np.arange(10)]*2).T

df = pd.DataFrame(data, index=[range(0, 10)], columns=colNames)

使用'myfunc'可以正常工作

using 'myfunc' this does work

df['D'] = (df.apply(lambda x: myfunc(x.A, x.B), axis=1))

但是第二种情况不起作用!

but this second case does not work!

df['D'] = (df.apply(lambda x: myfunc(x.colNames[0], x.colNames[1]), axis=1))

给出错误

AttributeError: ("'Series' object has no attribute 'colNames'", u'occurred at index 0')

我真的需要使用第二种情况(使用列表访问colNames),这会导致错误,以及如何执行此操作的任何线索?

I really need to use the second case (access the colNames using the list) which gives an error, any clues on how to do this?

谢谢

推荐答案

使用df.apply()时,DataFrame的每一行将作为熊猫系列传递给lambda函数.框架的列将成为该系列的索引,您可以使用series[label]访问值.

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

所以这应该起作用:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

这篇关于 pandas -使用apply()时,“系列"对象没有属性"colNames"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆