for 在创建新列时有很多 if 条件的循环

for loops with lots of if conditions while creating a new column

我正在尝试将 1 列(有点 2)的类别(字符串)转换为一组数字 1 代表恒星,2 qso,3 代表不是 agn 的星系(第二列定义)然后 4 代表AGN.all 保存在数据框的新列中的星系。

for n ,i, l in zip(data_clean['class'], data_clean['subClass'], data_clean['nClass'] ): 
if n == 'STAR':
    l = 1
elif n == 'QSO':
    l=2
elif n == 'GALAXY' and i != 'AGN':
    l=3
elif  n == 'GALAXY' and i == 'AGN': 
   l=4

其中 class 是主要类别,subclass 是我获得 AGN classification 的地方,nclass 是我放置新内容的新列整数class化。但我得到的都是零。我做错了什么?

这是你想要的吗?

def type_to_value(n, i):
    if n == 'STAR':
        return 1
    elif n == 'QSO':
        return 2
    elif n == 'GALAXY' and i != 'AGN':
        return 3
    elif n == 'GALAXY' and i == 'AGN': 
        return 4

data_clean['nClass'] = [type_to_value(n, i) for n, i in zip(data_clean['class'], data_clean['subClass'])]

你的 for 循环没有缩进?

尝试:

for n ,i, l in zip(data_clean['class'], data_clean['subClass'], data_clean['nClass'] ): 
    if n == 'STAR':
       l = 1
    elif n == 'QSO':
       l=2
    elif n == 'GALAXY' and i != 'AGN':
       l=3
    elif  n == 'GALAXY' and i == 'AGN': 
       l=4

我不能在此处使用制表符,所以请尝试在您的代码中使用 equal。请勿复制粘贴。