2016-03-14 1 views
2

В столбце class_name указано имя курса и номер когорты. Я хочу разделить столбец два столбца (имя, номер когорты)Использование pandas для разделения столбца и заполнения другого столбца с извлеченными значениями

ОТ:

| class_name | 

| introduction to programming 1th | 
| introduction to programming 2th | 
| introduction to programming 3th | 
| introduction to programming 4th | 
| algorithms and data structure 1th | 
| algorithms and data structure 2th | 
| object-oriented programming | 
| database systems | 

(я знаю, что это должно быть как 1-й, 2-й, 3-й, но строка на моем языке, и мы используем одни и те же символы снова и снова после номера).

TO:

| class_name | class_cohort | 

| introduction to programming | 1 | 
| introduction to programming | 2 | 
| introduction to programming | 3 | 
| introduction to programming | 4 | 
| algorithms and data structure | 1 | 
| alrogithms and data structure | 2 | 
| object-oriented programming | 1 | 
| database systems | 1 | 

Вот код, я работаю над:

import pandas as pd 

course_count = 100 
df = pd.read_csv("course.csv", nrows=course_count) 

cols_interest=['class_name', 'class_department', 'class_type', 'student_target', 'student_enrolled'] 

df = df[cols_interest] 
df.insert(1, 'class_cohort', 0) 

# this is how I extract the numbers 
df['class_name'].str.extract('(\d)').head() 

# but I cannot figure out a way to copy those values into column 'class_cohort' which I filled with 0's. 

# once I figure that out, I plan to discard the last digits 
df['class_name'] = df['class_name'].map(lambda x: str(x)[:-1]) 

Я кратко рассмотрел решение, в котором я бы поставить запятые все перед 1th, 2th, 3th, а затем разделить столбец с запятой в качестве разделителя, но я не мог найти способ заменить \ s1th ->, 1-й для всех чисел.

ответ

1

Вы можете indexing by positions:

df['class_cohort'] = df['class_name'].str[-3:-2] 
df['class_name'] = df['class_name'].str[:-4] 
print df 
    class_name class_cohort 
0  cs101   1 
1  cs101   2 
2  cs101   3 
3  cs101   4 
4 algorithms   1 
5 algorithms   2 

Или используйте str.extract:

df['class_cohort'] = df['class_name'].str.extract('(\d)') 
df['class_name'] = df['class_name'].str[:-4] 
print df 
         class_name class_cohort 
0 introduction to programming   1 
1 introduction to programming   2 
2 introduction to programming   3 
3 introduction to programming   4 
4 algorithms and data structure   1 
5 algorithms and data structure   2 
+0

Существовали некоторые детали, я оставил, - и \ S + не будет работать в этом случае, так как название курса состоит из нескольких слова (1-6 слов). – younghak

+0

Спасибо. Проверьте решение. – jezrael

+0

Спасибо - 'str.extract' работает хорошо. Я поддержал ваш ответ, но я слишком много нуба, и мой голос пока не обнародован. – younghak

Смежные вопросы