代码之家  ›  专栏  ›  技术社区  ›  desert_ranger

如何在不使用循环的情况下将Pandas字符串列转换为特定数字?

  •  0
  • desert_ranger  · 技术社区  · 3 年前

    我有一列字符串,我想把它们转换成特定的数字。我目前的方法包括使用for循环,但我觉得Pandas并不是这样设计的。有人能提出一个更优雅的解决方案,适用于多个专栏吗?

    这是我的代码-

    import pandas as pd
    data = [['mechanical@engineer', 'field engineer'], ['field engineer', 'lab_scientist'],
            ['lab_scientist', 'mechanical@engineer'], ['field engineer', 'mechanical@engineer'],
            ['lab_scientist','mechanical@engineer']]# Create the pandas DataFrame
    df = pd.DataFrame(data, columns=['Job1', 'Job2'])
    for index, row in df.iterrows():
        if row['Job1']=="mechanical@engineer":
            row['Job1'] = 0
        elif row['Job1']=="field engineer":
            row['Job1'] = 1
        elif row['Job1'] == "lab_scientist":
            row['Job1'] = 2
    print(df.head())
    
    2 回复  |  直到 3 年前
        1
  •  3
  •   akuiper    3 年前

    看起来你只需要一张地图:

    role_to_code = {"mechanical@engineer": 0, "field engineer": 1, "lab_scientist": 2}
    
    df.Job1.map(role_to_code)
    #0    0
    #1    1
    #2    2
    #3    1
    #4    2
    #Name: Job1, dtype: int64
    
        2
  •  1
  •   Phoenix    3 年前

    你为什么不使用 replace 函数而不是您的 for

    mapping = {'mechanical@engineer': 0, 'field engineer': 1, 'lab_scientist': 2}
    
    df = df.replace(mapping)
    
    print(df.head())
    

    输出将是:

       Job1  Job2
    0     0     1
    1     1     2
    2     2     0
    3     1     0
    4     2     0