【pandas】apply方法传入dataframe多列进行函数操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/84337586

参考:dataframe.apply官方文档

How to apply a function to two columns of Pandas dataframe

python pandas- apply function with two arguments to columns           

在处理数据的时候想做时间的转换,抽取生日(格式如 1994-10-5)提取月份和日期转换成星座,以下是星座转换function,需要传入month和day,已有的dataframe数据里已经有dataframe['月份'],dataframe['日'],即需要传入2列数据,转换得到dataframe['星座'](当然还有一个思路是 只传一个生日进去,然后在函数里split('-)提取月份和日,但是我就是想看看传多列参怎么解决而已hh)


def date2Constellation(month, day):
    cst = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座', u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
    date = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22), (7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
    return cst[len(list(filter(lambda y: y <= (month, day), date))) % 12]

 先来看看官方文档里的apply()

DataFrame.apply(funcaxis=0broadcast=Noneraw=Falsereduce=Noneresult_type=Noneargs=()**kwds)[source] 

Apply a function along an axis of the DataFrame.

 其中args=(),就是传入传入func的参数,所以我尝试了以下写法

    dataSet['星座'] = dataSet.apply(date2Constellation,args=(dataSet['出生月份'], dataSet['出生日']), axis=1)

然后报如下错

后来参考了stackoverflow,正确写法如下

  dataSet['星座'] =  dataSet.apply(lambda x :date2Constellation(x['出生月份'],x['出生日']),axis=1)

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/84337586
今日推荐