How to assign a list element with loc function in pandas df?

Viewed 342

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 Answers

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
Related