I have pandas dataframe column that contains both list and str values. I am only trying to convert str values into a proper list format so that it matches other list form values. I found a fix around it but I am looking to see if there is better way to do it? Below are my questions:
- If there is a pandas's build functionality/capability to use instead of writing long
regex,replace, ..etc? - How to convert
[nan]to[]without regex?
Here is my try:
Data File:
StudentName,CourseID
Alan,"['abc-12-0878', 'abc-12-45', 'abc-12-232342']"
Tim,"['abc-12-0878', 'abc-12-45']"
David,abc-12-1147
Martha,
Matt,"['abc-12-0878', 'abc-12-45']"
Abby,abc-12-1148
My code try:
import pandas as pd
df = pd.read_csv('sample_students.csv')
df
df['result'] = df['CourseID'].astype(str).apply(lambda x: x.strip('[]').replace("'","").split(','))
# Regex route.
# Pandas`s build in function available?
# gives `[nan]` instead of `[]`
# `to_list` and `tolist` didn't work.
Result I am looking for:
print(df[['CourseID','result']])
CourseID result
['abc-12-0878', 'abc-12-45', 'abc-12-232342'] ['abc-12-0878', 'abc-12-45', 'abc-12-232342']
['abc-12-0878', 'abc-12-45'] ['abc-12-0878', 'abc-12-45']
abc-12-1147 ['abc-12-1147']
NaN []
['abc-12-0878', 'abc-12-45'] ['abc-12-0878', 'abc-12-45']
abc-12-1148 [abc-12-1148]