1

I have a question regarding the loc function for my pandas DataFrame. First I want to check if the person is a student, then I would like to assign to first value of the list 'Course' for that specific student. The dataset is quite large so I would like to keep using the loc function.

import pandas as pd
df = pd.DataFrame([{'Person':'student 1', 'Course':['course 1']}, {'Person':'student 2','Course':['course 1', 'course 2']}, {'Person':'teacher 1','Course':['course 1', 'course 2']}])
print(df)

df.loc[df['c1'].str.contains('student'), 'main student course'] = #first element of the list in 'Course' column.

How can I do this?

1 Answer 1

3

You can use boolean indexing + .str[0] to access the first list element:

mask = df["Person"].str.contains("student")
df.loc[mask, "main student course"] = df.loc[mask, "Course"].str[0]
print(df)

Prints:

      Person                Course main student course
0  student 1            [course 1]            course 1
1  student 2  [course 1, course 2]            course 1
2  teacher 1  [course 1, course 2]                 NaN
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.