Pandas的序列包含AttributeError: 'Series'对象没有属性'contains'。

4

我的数据

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},
     ]

我的代码

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

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

发生错误
AttributeError: 'Series' object has no attribute 'contains'

我想实现这个效果,如何使用contains函数?

contains文档:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html#pandas.Series.str.contains.

我希望数据是:

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

4
str.contains 的翻译是“包含”。 - rafaelc
我的数据是字典,使用str.contains函数,返回nan。 - xin.chen
1个回答

2

最好使用与数据兼容的结构。使用DataFrame。

DataFrame提供更好的列和行操作。你的数据是二维的,即它有项目,每个项目有属性和值。因此,适合于2D结构,如DataFrame,而不是1D结构,如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

针对系列(不推荐)

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

选择使用序列的原因是什么?我不会使用序列。 - Vishnudev Krishnadas
更新的答案 @xin.chen。我不明白你所说的“leader”是什么意思。 - Vishnudev Krishnadas
为什么推荐系列,我刚接触pandas。 - xin.chen
我已将其添加到答案中,以便对其他人有所帮助。 - Vishnudev Krishnadas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接