目前,我正在使用两个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")
答案 0 :(得分:1)
在这种情况下,您要使用.applymap()
,因为您要更改每个单独的项目:
def convert(v):
return "$"+ "{:,}".format(v)
df2[["Num1_3", "Num2_3"]] = df2[["Num1", "Num2"]].applymap(convert)
print(df2)
收益:
Category Num1 Num2 Num1_2 Num2_2 Num1_3 Num2_3
0 a 1000 4000 $1,000 $4,000 $1,000 $4,000
1 b 2000 5000 $2,000 $5,000 $2,000 $5,000
2 c 3000 6000 $3,000 $6,000 $3,000 $6,000