按部分字符串筛选出数据帧行

2024-09-28 22:44:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是pandas的新手,我正在尝试通过从原始数据的一列中提取部分字符串来创建数据帧

recipe_info = {
    'title' = [ 'waffles', 'eggs', 'chocolate pancakes', 'pancakes']
    'rating' = [ 3.4, 2.8, 3,6, 1.5 ]

my_recipes = pd.DataFrame(recipe_info)

recipe_info[recipe_info['title'].str.contains("pancake")]

所需输出:

all_the_pancakes = {
     'title' = ['chocolate pancakes', 'pancakes']
     'rating' = [3.6, 1.5]

提前谢谢。。。你知道吗


Tags: 数据字符串infopandas原始数据titlemyrecipe
2条回答

Use也可以使用filter()

new_df =df.set_index('title').filter(like='pancakes', axis = 0).reset_index()

您需要:

recipe_info = {
    'title': [ 'waffles', 'eggs', 'chocolate pancakes', 'pancakes'],
    'rating': [ 3.4, 2.8, 3.6, 1.5 ]}


my_recipes = pd.DataFrame(recipe_info)

new_df = my_recipes[my_recipes['title'].str.contains('pancakes')]
print(new_df)

输出:

   rating               title                                                                                                         
2     3.6  chocolate pancakes                                                                                                         
3     1.5            pancakes   

相关问题 更多 >