【问题标题】:How to apply a function to get the encoded specific columns in pandas如何应用函数来获取熊猫中编码的特定列
【发布时间】:2020-07-21 13:37:27
【问题描述】:

我有这个功能:

get_class(cols):
    if cols == 1:
        return 1
    elif cols ==2:
        return 2
    else:
        return 0

我列出了一些这样的列:

cols = ['night', 'day']
cols_en = []

for each in cols:
    each = cols + '_en'
    cols_en.append(each)

在这里,我希望函数 get_class 应用于 cols 并在 cols_en 中获取输出。我想自动化这段代码:

df ['night_en'] = [1 if x==1 else 2 if x==2 else 0 for x in df['night']]

想法是将函数应用于列表cols 中的所有列并获取输出,其中列应用了函数get_class,输出列最后具有_en。也许也使用map 函数。有什么想法可以实现吗?我已经阅读了几篇类似的文章,但没有多大帮助。

【问题讨论】:

    标签: python pandas label-encoding


    【解决方案1】:

    IIUC,如果原来的值既不是1也不是2,你想用0创建一个新列,例如,你可以使用np.where。并在您的列表cols 上创建一个循环以创建新列

    for col in cols:
        df[f'{col}_en'] = np.where(df[col].isin([1,2]), df[col], 0)
    

    【讨论】:

    • 如果有条件怎么办。我在原始列中的值从 0 到 100,我希望 1 和 2 保持不变,但所有 3 或大于 3 的值都转换为 3
    • 并得到错误“方法对象不可下标”
    • @Arpit 我没有收到错误,因此如果需要帮助,您需要详细说明。对于您之前的评论,可能是np.where(df[col]<3, df[col], 3)
    猜你喜欢
    • 2021-07-29
    • 1970-01-01
    • 2021-07-12
    • 2018-12-25
    • 2023-02-10
    • 2019-12-30
    • 2020-10-01
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多