使用自定义函数迭代Pandas系列中的每个项目

时间:2016-08-18 02:37:45

标签: python pandas

我在Pandas中有一个数据框,列出了这样的信息:

           Player     Year    Height
1     Stephen Curry  2015-16  6-3
2   Mirza Teletovic  2015-16  6-10
3        C.J. Miles  2015-16  6-7
4  Robert Covington  2015-16  6-9

现在data ['Height']将其值存储为字符串,我想将这些值转换为英寸存储区作为整数进行进一步计算。

我尝试了一些方法,包括Pandas文档中列出的内容,但无济于事。

首次尝试

def true_height(string):
    new_str = string.split('-')
    inches1 = new_str[0]
    inches2 = new_str[1]

    inches1 = int(inches1)*12
    inches2 = int(inches2)

    return inches1 + inches2

如果你跑

true_height(data.iloc[0, 2])

它返回75,正确的答案。

要在整个系列中运行它,我更改了这行代码:

new_str = string.**str**.split('-') 

然后跑了:

data['Height'].apply(true_height(data['Height']))

并收到以下错误消息:

int() argument must be a string or a number, not 'list'

然后我尝试使用for循环,认为可以解决这个问题,所以我将原始公式修改为:

def true_height(strings):
for string in strings:
    new_str = string.split('-')
    inches1 = new_str[0]
    inches2 = new_str[1]

    inches1 = int(inches1)*12
    inches2 = int(inches2)

    return inches1 + inches2

现在我收到以下错误:

'int' object is not callable

当我跑步时:

data['Height'].apply(true_height(data['Height']))

我有点难过。任何帮助,将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以在将Height列拆分为列表后使用apply并将lambda函数传递给它进行转换:

df['Height'] = df.Height.str.split("-").apply(lambda x: int(x[0]) * 12 + int(x[1]))

df
#             Player       Year    Height
# 1    Stephen Curry    2015-16        75
# 2  Mirza Teletovic    2015-16        82
# 3       C.J. Miles    2015-16        79
# 4 Robert Covington    2015-16        81

或者使用最初定义的true_height功能(第一次尝试)和apply

df['Height'] = df.Height.apply(true_height)

您不需要将df.Height传递给函数,因为apply会将函数作为参数接收。

答案 1 :(得分:1)

df['feet'], df['inches'] = zip(*df.Height.str.split('-'))

df['feet'] = df.feet.astype(int)
df['inches'] = df.inches.astype(float)
df['height_inches'] = df.feet * 12 + df.inches

>>> df
              Player     Year Height  feet  inches  height_inches
1 Stephen      Curry  2015-16    6-3     6       3             75
2 Mirza    Teletovic  2015-16   6-10     6      10             82
3 C.J.         Miles  2015-16    6-7     6       7             79
4 Robert   Covington  2015-16    6-9     6       9             81
相关问题