【问题标题】:Converting 'no' and 'yes' into 0 and 1 in pandas dataframe [duplicate]在熊猫数据框中将“否”和“是”转换为0和1 [重复]
【发布时间】:2019-01-11 08:27:04
【问题描述】:

我想转换包含 int 以及 'yes' 和 'no' 值的 'edjefe' 列的数据。我的问题是我只想将“是”和“否”映射到 1 和 0 并保持 int 值不变 所以我写了这段代码

def foo(x):
    if x == 'no':
        return 0
    elif x == 'yes':
        return 1
    else:
        return x

df1.edjefe.map(lambda x : foo(x))

但我得到一个错误,

RecursionError: maximum recursion depth exceeded while calling a Python object

【问题讨论】:

  • 完整追溯在哪里?
  • 可能是 apply 函数而不是 map。但是如果没有工作示例,很难评估错误
  • 问题与machine-learning(或numpy)无关 - 请不要向标签发送垃圾邮件(已删除)
  • apply 出现同样的错误

标签: python pandas series


【解决方案1】:

您也可以使用 pandas.Categorical。

df1["edjefe"] = pd.Categorical(df1["edjefe"]).codes

访问here了解更多信息。

【讨论】:

    【解决方案2】:

    你也可以试试:

    df1['edjefe'] = (df1['edjefe']=="yes")*1 
    

    【讨论】:

      【解决方案3】:

      您可以将pd.Series.map 与字典映射一起使用,后跟pd.Series.fillna

      d = {'no': 0, 'yes': 1}
      df1['edjefe'] = df1['edjefe'].map(d).fillna(df1['edjefe'])
      

      您可能会发现这比 pd.Series.replace 更有效。

      更多详情请见Replace values in a pandas series via dictionary efficiently

      如果您的系列中有可变对象,这将失败,因为字典键必须是可散列的。在这种情况下,您可以转换为字符串:

      df1['edjefe'] = df1['edjefe'].astype(str).map(d).fillna(df1['edjefe'])
      

      【讨论】:

      • 我收到TypeError: 'Series' objects are mutable, thus they cannot be hashed 错误
      • @JaqenH'ghar,你能提供一个minimal reproducible example吗?我无法复制您的错误。
      • @JaqenH'ghar,另外,请参阅更新。看来您的系列中可能有 list 或其他可变类型。
      • 知道了,0 和 1 是 str 类型。 Tnx
      • @JaqenH'ghar,不,这是不正确的。我们正在将系列元素转换为 str 作为中间步骤,以确保元素是可散列的。
      【解决方案4】:

      只需使用类似dict的to_replace

      df['edjefe'].replace({'no': 0, 'yes': 1})
      

      【讨论】:

      • 所有列呢?
      • @mLstudent33,只需在整个 DataFrame 上使用 replace,而不是特定列:df.replace({'no': 0, 'yes': 1})
      【解决方案5】:

      你也可以只使用replace:

      df.edjefe.replace(to_replace=['no', 'yes'], value=[0, 1])

      【讨论】:

      • TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'
      • 字符串替换需要一个字符串作为输入和输出。将 yes 和 no 替换为 value=['0', '1'],然后将结果转换为 int()
      猜你喜欢
      • 2017-12-19
      • 1970-01-01
      • 2021-05-05
      • 2020-09-08
      • 2018-05-03
      • 2019-05-25
      • 1970-01-01
      • 2020-12-01
      • 2020-09-08
      相关资源
      最近更新 更多