【问题标题】:How to use series. apply() to create conditional pandas series?如何使用系列。 apply() 创建有条件的熊猫系列?
【发布时间】:2020-06-26 13:28:54
【问题描述】:

我正在尝试使用来自另一列的数字数据在我的 df 中创建一个新列。我尝试使用 for 循环和一系列 if 语句将数值数据分类为我现在要用于创建新列的字符串。以下数据来自 WNBA 2010-2011 球员数据集。

def clean(col):  
    for xp in col:
        if xp < 1:
            print('Rookie')
        elif ((xp >= 1) and (xp <= 3)):
            print('Little experience')
        elif ((xp >= 4) and (xp <= 5)):
            print('Experienced')
        elif ((xp > 5) and (xp < 10)):
            print('Very experienced')
        elif (xp > 10):
            print("Veteran")

我尝试使用 series.apply() 和 series.map() 但这两个都返回一个名为 XP 的新列,如下所示

XP = df.Experience.apply(clean) 
df['XP'] = XP

但是,当我检查 dtypes 时,它说新创建的列是 NONETYPE 对象。这是因为我在 for 循环中使用 print 函数而不是操作实际值吗?如果是这样,我应该怎么做才能返回指定的字符串值?

提前感谢您的帮助。

【问题讨论】:

标签: python pandas for-loop if-statement


【解决方案1】:
df = pd.DataFrame({'xp':[0,2,4,6,20,'4']})

输入一个字符串,因为你有类型错误。

def clean(str_xp):
     xp = int(str_xp)
     if xp < 1: 
         return('Rookie') 
     elif ((xp >= 1) and (xp <= 3)): 
         return('Little experience') 
     elif ((xp >= 4) and (xp <= 5)): 
         return('Experienced') 
     elif ((xp > 5) and (xp < 10)): 
         return('Very experienced') 
     elif (xp > 10): 
         return ("Veteran") 

df['rank'] = df['xp'].apply(clean) 

df 返回:

   xp               rank
0   0             Rookie
1   2  Little experience
2   4        Experienced
3   6   Very experienced
4  20            Veteran
5   4        Experienced

【讨论】:

  • 感谢您的回复。我想知道为什么在您的输出的索引号 5 上,xp 值为 4,而初始列表中使用了字符串“5”?对不起,我是 python 新手。如果可以的话,我将不胜感激?再次感谢
  • 现在编辑,现在应该是这样
【解决方案2】:

那是因为你的函数没有返回任何东西(所以默认返回 None )。您需要用return 替换那些print 语句。

另外,您不需要循环遍历函数中的列 - apply 以矢量化方式为您执行此操作。试试这个:

def clean(xp):  
    if xp < 1:
        return 'Rookie'
    elif ((xp >= 1) and (xp <= 3)):
        return 'Little experience'
    elif ((xp >= 4) and (xp <= 5)):
        return 'Experienced'
    elif ((xp > 5) and (xp < 10)):
        return 'Very experienced')
    elif (xp > 10):
        return "Veteran"

df['XP'] = df.Experience.apply(clean)

还要记住,根据当前编写等式的方式,如果xp == 10,您的函数将返回None

【讨论】:

  • 感谢西蒙的回复。我尝试了你的建议,它给了我一个类型错误 TypeError: 'int' object is not iterable。应该提到 df.Experience 列是一种干扰 dtype。
  • 重新启动内核并收到此错误 TypeError: '
  • 嘿 Oscar,这可能是因为您的某些输入是字符串,也许我的代码可以解决这个问题。
猜你喜欢
  • 2020-04-23
相关资源
最近更新 更多