确定几个数据框在 Pandas 中是否具有相同的列名 [英] Determining if several data frames have the same column names in pandas

查看:47
本文介绍了确定几个数据框在 Pandas 中是否具有相同的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个 df,想确定它们是否都具有相同的列名.我看过几个例子,其中使用两个数据框完成此操作,但想了解有关如何跨多个 df-s 执行此操作的信息.

I have several df and would like to determine if they all have the same column names. I have seen several examples where this is done with two data frames but wanted some information on how to do this across multiple df-s.

例如,如果我有一个 df-s 列表

For example if I have a list of df-s

dataframes = [df_1, df_2, df_3, df_4, df_5_1, df_5_2, df_6_1, df_6_2]

我想遍历每一个,看看它们是否都包含相同的列名.

I would like to possibly loop through each one to see if they all contain the same column names.

推荐答案

假设您没有重复的列名,这在 pandas 中绝不是一个好主意,而相同"则不是关心它们在索引中出现的位置,检查列索引的长度是否与两个 DataFrame 索引之间的集合交集的长度相同就足够了.

Assuming your don't have duplicate column names, which is never a good idea in pandas, and "same" doesn't care about the position they occur in the Index, it suffices to check if the length of the columns index is the same as the length of the set intersection between two DataFrame indices.

因为您想知道它们是全部相同还是任何单个不同,所以检查第一个就足够了.

Because you want to know whether they are all the same or if any single one differs, it suffices to check against the first.

all([len(dataframes[0].columns.intersection(df.columns)) 
      == dataframes[0].shape[1] for df in dataframes])

这篇关于确定几个数据框在 Pandas 中是否具有相同的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆