【问题标题】:How do I swap first and last names with a comma and add a new column?如何用逗号交换名字和姓氏并添加新列?
【发布时间】:2019-08-25 15:43:28
【问题描述】:

我有一个数据框,其中索引是名称。但是名字是名字,姓氏*

数据是这样的

Index          Sales
Jones, Mike*   500
James, Amy     300 

目标是拥有(或将索引更改为名称)

Index         Sales    Special 
Mike Jones     500       1
Amy James      300       0

如果有 * 则创建一个新列,如果有 * 则为 1,如果没有则为 0?

【问题讨论】:

    标签: python pandas dataframe indexing


    【解决方案1】:

    假设Index为索引列:

    In [32]: df['Special'] = df.index.str.endswith('*').astype(int)                                                 
    
    In [33]: df.set_index(df.index.str.replace(r'^(\w+),\s+(\w+)\*?', '\\2 \\1', regex=True))                       
    Out[33]: 
                Sales  Special
    Index                     
    Mike Jones    500        1
    Amy James     300        0
    

    详情:

    • df.index.str.endswith('*').astype(int) - 检查index 列值是否以* 结尾并将逻辑结果转换为整数值(为01
    • df.index.str.replace(r'^(\w+),\s+(\w+)\*?', '\\2 \\1', regex=True)- 将index 列值替换为第一个和第二个正则表达式捕获组的内容(\w+)\\2 \\1 交换它们的位置(第二个后跟第一个)

    【讨论】:

    • 你能解释一下replace是如何交换名字和姓氏的同时还删除*的吗?
    • @IanThompson,是的。看我的解释
    【解决方案2】:
    # swap the first name and last name by splitting on the comma then using the .str attribute and reversing the list
    print(df.index.str.split(',').str[::-1])
    
    Index([[' Mike*', 'Jones'], [' Amy', 'James']], dtype='object')
    
    # convert to series and .join the values in each row, then set as the index
    df.set_index(pd.Series(df.index.str.split(',').str[::-1]).apply(lambda x : ' '.join(x)), inplace=True)
    print(df)
    
                  Sales
     Mike* Jones    500
     Amy James      300
    
    # create a new column called "Special" and check where the index contains a "*"
    # note you have to use "\*" because * is a special character
    df['Special'] = df.index.str.contains('\*').astype(int)
    print(df)
    
                  Sales  Special
     Mike* Jones    500        1
     Amy James      300        0
    
    # reassign the index after you replace the * with a blank ''
    df.index = df.index.str.replace('\*', '')
    print(df)
    
                 Sales  Special
     Mike Jones    500        1
     Amy James     300        0
    

    【讨论】:

      【解决方案3】:

      我可以看到的一个快速解决方案是使用iterrows()。您首先将special 列初始化为全零df['special']=0。然后遍历更正每个索引的行,并在需要的地方使特殊等于 1。

      类似的东西

      for i,j in df.iterrows():
          if '*' in i:
                  df.loc[i]['Special'] = 1
          df.rename(index={i: (i.split(',')[1] +' '+ i.split(',')[0]).replace('*','')}, inplace=True)
      

      希望这会有所帮助。

      【讨论】:

        【解决方案4】:

        假设df 是您的数据框,'Index' 是索引。如果 'Index' 只是一列,请删除 reset_indexset_index 调用。

        ddf = df.reset_index()
        ddf['Special'] = ddf['Index'].str.contains('\*').astype(int)
        ddf['Index'] = ddf['Index'].apply(lambda x : ' '.join(x.split(',')[::-1]).replace('*', '').strip())
        ddf.set_index('Index', inplace=True)
        

        ddf 是结果:

                    Sales  Special
        Index                     
        Mike Jones    500        1
        Amy James     300        0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-17
          • 2016-02-22
          • 1970-01-01
          • 2014-10-07
          相关资源
          最近更新 更多