1 回答

TA贡献1835条经验 获得超7个赞
您创建的函数 ( change_columns(df)) 似乎正在尝试对所有列执行替换。如果这是您的意图,那么您不需要任何特殊的函数或链式方法调用。所有你需要的是:
dados_trabalho = dados_trabalho.replace({0: "Sim", 1 : "Não"})
为了仅替换某些列中的 0 和 1,您需要告诉函数您要对哪些列执行替换。例如:
import pandas
def change_columns(df, cols):
for col_name in cols:
df = df.replace({col_name: {0:'yes', 1:'no'}})
return df
# create sample data
df = pandas.DataFrame([[0, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0]])
print('Starting DataFrame:')
print(df)
# define columns to do the replacement
columns_to_replace = [0, 2, 3]
# perform the replacement
df = change_columns(df, columns_to_replace)
# see the result
print('After processing DataFrame: ')
print(df)
运行上面的代码应该会产生结果:
Starting DataFrame:
0 1 2 3 4 5
0 0 0 1 0 1 1
1 1 0 1 0 1 0
After processing DataFrame:
0 1 2 3 4 5
0 yes 0 no yes 1 1
1 no 0 no yes 1 0
添加回答
举报