【问题标题】:python customized map() function does not runpython自定义map()函数不运行
【发布时间】:2018-04-17 10:14:32
【问题描述】:

我想跨列将字符串值映射到整数。我已经编写了自定义代码。但是,当我调用代码并传递我的列表时,它什么也没做。有没有我遗漏的语法?

def encode_cols(myList = [], *args):
    for col in myList:
        if col == 'Lot Shape':
            df[col] = df[col].map({'Reg':4, 'IR1':3, 'IR2':2, 'IR3':1})
        if col == 'Utilities':
            df[col] = df[col].map({'AllPub':4, 'NoSwer':3, 'NoSeWa':2, 'ELO':1})
        if col == 'Land Slope':
            df[col] = df[col].map({'Gtl':3, 'Mod':2,'Sev':1})

lst = ['Lot Shape','Utilities','Land Slope']
encode_cols(lst)

【问题讨论】:

  • 我想你忘了return df
  • 好的,马上试试。我将 return 添加到每个单独的行而不是将它们添加到末尾。
  • @Zoozoo 你的代码在这里引发NameError

标签: python pandas dataframe


【解决方案1】:

您的函数不返回任何内容,并且您的列表未正确定义。

更 Pandonic 的选择是使用pd.DataFrame.pipe

def encode_cols(df, myList):
    for col in myList:
        if col == 'Lot Shape':
            df[col] = df[col].map({'Reg':4, 'IR1':3, 'IR2':2, 'IR3':1})
        if col == 'Utilities':
            df[col] = df[col].map({'AllPub':4, 'NoSwer':3, 'NoSeWa':2, 'ELO':1})
        if col == 'Land Slope':
            df[col] = df[col].map({'Gtl':3, 'Mod':2,'Sev':1})
    return df

lst = ['Lot Shape', 'Utilities', 'Land Slope']

df = df.pipe(encode_cols, lst)

【讨论】:

  • 我意识到我的第一个错误并对其进行了编辑。我会按照建议尝试。感谢您向我介绍管道。直到现在才知道它的存在。我猜我可以在 Python 文档上阅读更多内容?
  • 是的,已将链接添加到我的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2018-09-24
  • 2022-06-11
  • 1970-01-01
相关资源
最近更新 更多