【发布时间】: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 函数而不是操作实际值吗?如果是这样,我应该怎么做才能返回指定的字符串值?
提前感谢您的帮助。
【问题讨论】:
-
对您的标题的最佳答案是您不应该这样做。
.apply是一个慢循环,在 pandas 中你会选择使用np.select: stackoverflow.com/questions/19913659/…
标签: python pandas for-loop if-statement