我有一些excel文件并不总是结构相同;所以我用headers = None参数读取pandas数据帧。
然后我做了一些检查以获得标题行索引位置。 我有一个必须列的列表,我需要在传递行索引之前检查。
mandatory_cols = ['items','name','email']
我的数据框:
0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
3 items email name store
4 2 test Mike 2
我需要返回3
,因为第3行包含我的列表中包含的所有项目。如果缺少任何返回无。
我看过df.isin(mandatory_cols)
,但它似乎只返回一个bools的数据框,我似乎无法弄清楚如何只得到索引。
有些注意事项,列位置可能在文件中乱序,因此我需要能够使用此检查动态查看所有列。此行还可以包含多个mandatory_cols,只要它具有我希望索引位置的所有必需列。
谢谢!
答案 0 :(得分:4)
IIUC,您应该使用issubset
,而不是isin
df[[set(mandatory_cols).issubset(x) for x in df.values.tolist()]].index
Out[1098]: Int64Index([3], dtype='int64')