熊猫-将Lambda转化为功能

目前,我正在使用两个lambda函数向数据集中的两列添加一千个分隔符和一个$符号,但是我想使代码更高效。我尝试将其转换为函数,因此不必重复执行代码,但是无法使其正常工作。

df2 = pd.DataFrame({"Category": ["a", "b", "c"], "Num1": [1000, 2000, 3000], "Num2": [4000, 5000, 6000]})

# This works, but I don't want to use those two repetitive lines of code
df2["Num1_2"] = df2.apply(lambda x: "$"+ "{:,}".format(x['Num1']), axis=1)
df2["Num2_2"] = df2.apply(lambda x: "$"+ "{:,}".format(x['Num2']), axis=1)

# I tried writing this function instead
def convert(column):
    "$"+ "{:,}".format(column)
    return column

# This returns an error: KeyError: "None of [Index(['Num1', 'Num2'], dtype='object')] are in the [columns]"
df[["Num1_2", "Num2_2"]] = df[["Num1", "Num2"]].apply(convert, axis = "columns")
评论