Я думаю, что ваше решение хорошо, если списки в столбце List
:
print (type(df.iat[0, df.columns.get_loc('List')]))
<class 'list'>
df['Len'] = df['List'].str.len()
Решение, если не пропущены значения:
df['Len'] = df['List'].apply(len)
Если нет, сначала удалитевозможно ,
в начале конца на Series.str.strip
, а затем считать число ,
с помощью Series.str.count
:
print (type(df.iat[0, df.columns.get_loc('List')]))
<class 'str'>
df['Len'] = df['List'].str.strip(' ,[]').str.count(',') + 1
print (df)
List Len
2013-12-22 15:25:02 [good morning, good afternoon, good evening] 3
2009-12-14 14:29:32 [happy new year, happy birthday,] 2
2013-12-22 15:42:00 [happy, sad, mad, chill] 4
Если необходимо также преобразоватьзначения в списках:
df['List'] = df['List'].str.strip(' ,[]').str.split(', ')
print (type(df.iat[0, df.columns.get_loc('List')]))
<class 'list'>
df['Len'] = df['List'].str.len()
print (df)
List Len
2013-12-22 15:25:02 [good morning, good afternoon, good evening] 3
2009-12-14 14:29:32 [happy new year, happy birthday] 2
2013-12-22 15:42:00 [happy, sad, mad, chill] 4