В столбце 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-й для всех чисел.
Существовали некоторые детали, я оставил, - и \ S + не будет работать в этом случае, так как название курса состоит из нескольких слова (1-6 слов). – younghak
Спасибо. Проверьте решение. – jezrael
Спасибо - 'str.extract' работает хорошо. Я поддержал ваш ответ, но я слишком много нуба, и мой голос пока не обнародован. – younghak