Python – Pandas’ series contains AttributeError: ‘Series’ object has no attribute ‘contains’

pandaspython

My data

data = [{"content": "1", "title": "chestnut", "info": "", "time": 1578877014},
     {"content": "2", "title": "chestnut", "info": "", "time": 1579877014},
     {"content": "3", "title": "ches", "info": "", "time": 1582877014},
     {"content": "aa", "title": "ap", "info": "", "time": 1582876014},
     {"content": "15", "title": "apple", "info": "", "time": 1581877014},
     {"content": "16", "title": "banana", "info": "", "time": 1561877014},
     ]

Mycode

index=[i['content'] for i in data]

s=pd.Series(data,index)
print((s[s.str.get('title').contains('ches',regex=True)]))

Error occured

AttributeError: 'Series' object has no attribute 'contains'

I want to achieve this effect, how do I use contains
contais document:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html#pandas.Series.str.contains.

I want the data to be

[
{"content": "1", "title": "chestnut", "info": "", "time": 1578877014},
{"content": "2", "title": "chestnut", "info": "", "time": 1579877014},
{"content": "3", "title": "ches", "info": "", "time": 1582877014},
]

Best Answer

Its better to have a structure that is compatible to the data. Use a dataframe.

DataFrame provides better manipulation of columns and rows. Your data is 2 dimensional i.e. it has items and then each item has attribute with values. Hence fitting into a 2D structure like DataFrame and not a 1D structure like Series.

>>> df = pd.DataFrame(data)
>>> df
  content     title info        time
0       1  chestnut       1578877014
1       2  chestnut       1579877014
2       3      ches       1582877014
3      aa        ap       1582876014
4      15     apple       1581877014
5      16    banana       1561877014

>>> df[df.title.str.contains('ches')]
  content     title info        time
0       1  chestnut       1578877014
1       2  chestnut       1579877014
2       3      ches       1582877014

For series (Not recommended)

s[s.apply(lambda x: x.get('title')).str.contains('ches')]