代码之家  ›  专栏  ›  技术社区  ›  Aptha Gowda

在pandas数据帧中将“no”和“yes”转换为0和1

  •  2
  • Aptha Gowda  · 技术社区  · 7 年前

    我想转换包含int以及“yes”和“no”值的“edjefe”列的数据。我的问题是我只想将“yes”和“no”映射到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
    
    3 回复  |  直到 7 年前
        1
  •  8
  •   ksbg    7 年前

    你也可以用 replace :

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

        2
  •  3
  •   jpp    7 年前

    你可以用 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'])
    
        3
  •  0
  •   Lev Zakharov Riss    7 年前

    用dict-like to_replace :

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