如何使用 .replace 减少命令和创建函数中的问题

我有一个数据框,我想在我选择的某些列中用“是”和“否”替换 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


绝地无双
浏览 155回答 1
1回答

qq_花开花谢_0

您创建的函数 ( change_columns(df)) 似乎正在尝试对所有列执行替换。如果这是您的意图,那么您不需要任何特殊的函数或链式方法调用。所有你需要的是:dados_trabalho = dados_trabalho.replace({0: "Sim", 1 : "Não"})为了仅替换某些列中的 0 和 1,您需要告诉函数您要对哪些列执行替换。例如:import pandasdef change_columns(df, cols):&nbsp; &nbsp; for col_name in cols:&nbsp; &nbsp; &nbsp; &nbsp; df = df.replace({col_name: {0:'yes', 1:'no'}})&nbsp; &nbsp; return df# create sample datadf = pandas.DataFrame([[0, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0]])print('Starting DataFrame:')print(df)# define columns to do the replacementcolumns_to_replace = [0, 2, 3]# perform the replacementdf = change_columns(df, columns_to_replace)# see the resultprint('After processing DataFrame: ')print(df)运行上面的代码应该会产生结果:Starting DataFrame:&nbsp; &nbsp;0&nbsp; 1&nbsp; 2&nbsp; 3&nbsp; 4&nbsp; 50&nbsp; 0&nbsp; 0&nbsp; 1&nbsp; 0&nbsp; 1&nbsp; 11&nbsp; 1&nbsp; 0&nbsp; 1&nbsp; 0&nbsp; 1&nbsp; 0After processing DataFrame:&nbsp; &nbsp; &nbsp;0&nbsp; 1&nbsp; &nbsp;2&nbsp; &nbsp; 3&nbsp; 4&nbsp; 50&nbsp; yes&nbsp; 0&nbsp; no&nbsp; yes&nbsp; 1&nbsp; 11&nbsp; &nbsp;no&nbsp; 0&nbsp; no&nbsp; yes&nbsp; 1&nbsp; 0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python