【问题标题】:Iterating Over Every Item in a Series in Pandas With A Custom Function使用自定义函数迭代 Pandas 系列中的每个项目
【发布时间】:2016-08-18 10:59:00
【问题描述】:

我在 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']))

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

【问题讨论】:

  • 我希望你在def true_height(strings): 行之后缩进。

标签: python pandas


【解决方案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 接收函数作为参数。

【讨论】:

  • 我还不能将此标记为已回答,但非常感谢您,工作就像一个魅力。我还没有非常多地使用 lambda 表示法,这非常有用。一个问题:您在一个地方使用 df['Height'] 并在其他地方使用 df.Height 是否有特殊原因?非常感谢。
  • 没有特别的原因。我只是发现.Height 节省了一点打字时间。但是在分配给数据框中不存在的新变量时不能使用它。所以我必须在左侧使用[''],这成为了一种习惯。
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 1970-01-01
    • 2017-11-05
    • 2022-09-29
    • 2018-01-29
    • 2021-12-26
    • 2011-01-13
    • 2011-11-24
    • 1970-01-01
    相关资源
    最近更新 更多