我有一个数据框,我想在其中选择的某些列中将0、1编码替换为“是”和“否”。一些df列具有这种编码,因此我编写了以下命令:
dados_trabalho = dados_trabalho.replace({"ASSINTOM": {0: "Sim", 1 : "Não"}}).replace({"DOR ATIPICA": {0: "Sim", 1 : "Não"}}).replace({"IAM": {0: "Sim", 1 : "Não"}}).replace({"HAS": {0: "Sim", 1 : "Não"}}).replace({"DM": {0: "Sim", 1 : "Não"}}).replace({"DISPLIP": {0: "Sim", 1 : "Não"}}).replace({"DOR TIPICA": {0: "Sim", 1 : "Não"}})
它可以正常运行并替换新编码所标识的列,但是我想知道是否有一种方法可以汇总此公式,以使脚本不会太大。
我试图创建函数:
def change_columns (df):
c = df.columns
df = df.replace ({c: {0: "Yes", 1: "No"}})
问题是,当我在此函数中输入数据框时,会发生以下错误:
change_columns (df)
TypeError Traceback (most recent call last)
<ipython-input-141-43eb9316b19b> in <module>
----> 1 change_columns (df)
<ipython-input-140-9fbbd4e9e293> in change_columns (df)
1 def change_columns (df):
2 c = df.columns
----> 3 df = df.replace ({c: {0: "Yes", 1: "No"}})
/usr/lib/python3/dist-packages/pandas/core/indexes/base.py in __hash __ (self)
2060
2061 def __hash __ (self):
-> 2062 raise TypeError ("unhashable type:% r"% type (self) .__ name__)
2063
2064 def __setitem __ (self, key, value):
TypeError: unhashable type: 'Index'
我从Python开始,所以我想忘记了一些东西。
我更改了代码中的一些内容,并且可以正常工作。但是问题在于它在所有df列中都应用了该函数。如何仅在需要的列上应用该功能,而不在所有列上应用该功能?
def change_columns(df):
for i in df.columns:
df = df.replace({i: {0: "Sim", 1 : "Não"}})
return df
答案 0 :(得分:1)
您创建的函数(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