首页 > 解决方案 > 从索引列中的行中提取最后一个单词

问题描述

我需要有关如何从索引值中提取最后一个单词的建议。

我的数据集看起来像

                                                  Exercise 1        Exercise 2  ....
Homeworks                             Teacher      

/Users/school/Maths/Exercises on LD       GK         This exercise...   The second exercise needs ...         
... rows ...                              GK
/Users/school/Maths/Exercises on DE       MG
... rows ...                              MG
/Users/school/Maths/Exercises on GE       GD
... rows ...                              GD

和类似的其他路径的名称。练习 1 和 2 是列;Homeworks 和 Teacher 是索引列。

我需要将索引列中的值重命名如下(预期输出):

                           Exercise 1        Exercise 2  ....
   Homeworks    Teacher                               
    
    LD             GK        This exercise...   The second exercise needs ...
    ... rows ...   GK
    DE             MG
    ... rows ...   MG
    GE             GD
    ... rows ...   GD

我已经这样做了:

df.index = pd.MultiIndex.from_arrays([df.index.str.extract('\s(\w)\/$')[0]], 
                                         names=['Homeworks', 'Teacher'])

我必须使用 Multiindex,因为我有两列作为索引。你能告诉我如何得到上面的表格吗?

标签: pythonpandas

解决方案


鉴于以下情况:

import pandas as pd

data = {'Homeworks': ['//Users//school//Maths//Exercises1 on LD', '//Users//school//Maths//Exercises2 on DE', '//Users//school//Maths//Exercises3 on GE'],
        'Teacher': ['GK', 'MG', 'GD'],
        'Exercise 1': ['This exercise', 'This exercise', 'This exercise'],
        'Exercise 2': ['The second exercise needs', 'The second exercise needs', 'The second exercise needs']}

df = pd.DataFrame(data)
df.set_index(['Homeworks', 'Teacher'], inplace=True)

# display(df)
                                                     Exercise 1                 Exercise 2
Homeworks                                Teacher                                          
//Users//school//Maths//Exercises1 on LD GK       This exercise  The second exercise needs
//Users//school//Maths//Exercises2 on DE MG       This exercise  The second exercise needs
//Users//school//Maths//Exercises3 on GE GD       This exercise  The second exercise needs

更新df

  • 重置索引
  • 从最后 2 个字母创建一个新列Homeworks
  • (可选)从Homeworks
  • 设置新索引
df.reset_index(inplace=True)
df['Drives'] = df.Homeworks.str[-2:]  # take the last to letters
df['Paths'] = df.Homeworks.str.split(expand=True)[0]  # split on space and take the value at index 0
df.drop(columns=['Homeworks'], inplace=True)
df.set_index(['Drives', 'Teacher'], inplace=True)  # set the index

# display(df)
                   Exercise 1                 Exercise 2                               Paths
Drives Teacher                                                                              
LD     GK       This exercise  The second exercise needs  //Users//school//Maths//Exercises1
DE     MG       This exercise  The second exercise needs  //Users//school//Maths//Exercises2
GE     GD       This exercise  The second exercise needs  //Users//school//Maths//Exercises3

推荐阅读