在数据帧列的列表中搜索,E

2024-09-29 21:43:46 发布

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

形势 我在处理一个有1000多个表的数据库时遇到了这个问题。我想根据列名值筛选表名。我试图在我的数据帧上运行str.contains(),但出现了一个错误。错误读取"None of [Float64Index([nan, nan, nan, nan, nan], dtype='float64')] are in the [columns]"我能够用伪数据重现错误。你知道吗

我的目标是返回筛选到“table5”的数据帧,因为它包含列名“date”

listoftables = ['table1', 'table2', 'table3', 'table4', 'table5']
columnnames = [['age', 'name', 'school'], 
               ['age', 'name', 'school'], 
               ['age', 'name', 'school'], 
               ['age', 'name', 'school'], 
               ['audit', 'auditrunlist', 'date']]


example = pd.DataFrame(
    {'TableName': listoftables,
     'col_names'  : columnnames
    })

example[(example['col_names'].str.contains('date'))]

我认为这个错误是因为我在列表中搜索字符串。更让我困惑的是,如果我运行example[(example['col_names'].str.contains('[audit, auditrunlist, date]'))],我会得到同样的错误。你知道吗

如果我再添加一个不是列表的列,我会得到预期的结果


listoftables = ['table1', 'table2', 'table3', 'table4', 'table5']
columnnames = [['age', 'name', 'school'], 
               ['age', 'name', 'school'], 
               ['age', 'name', 'school'], 
               ['age', 'name', 'school'], 
               ['audit', 'auditrunlist', 'date']]

no_list_columnnames = ['age, name, school', 
               'age name school', 
                'age name school', 
               'age name school', 
               'audit auditrunlist date']


example = pd.DataFrame(
    {'TableName': listoftables,
     'col_names'  : columnnames,
     'no_list_col_names' : no_list_columnnames
    })

# this returns what i expect
example[(example['no_list_col_names'].str.contains('date'))]

我想我有两个结果,我可以尝试在pandas数据框中的列表中搜索,或者我可以找到一种方法将pandas数据框中的列从列表转换为字符串。你知道吗

用列表作为列过滤数据帧的更好方法是什么?你知道吗


Tags: 数据name列表agedatenamesexample错误
2条回答

这可以通过多种方式实现。你知道吗

过滤器

example = example[[True if ('date' in i) else False for i in example['col_names']]]

展开列表,然后筛选。代码看起来会更好,但可能需要更多的空间。你知道吗

example = example.explode('col_names')
example = example[example['col_names'] == 'date']

谢谢你指出这个问题很有趣

我的方法是使用经典的apply来创建一个标志

df['flag']=df.apply(lambda x: 1 if 'date' in x['col_names'] else 0, axis=1)

在我过滤之后:

df_filtered=df.loc[df['flag']==1,:]

也许他们有聪明的选择,但这样做的工作

相关问题 更多 >

    热门问题