python - 如何使用Python根据列名找出两个数据框的差异

标签 python python-3.x pandas

我想找出两个数据框在列名方面的区别。

这是示例表 1

d1 = {'row_num': [1, 2, 3, 4, 5], 'name': ['john', 'tom', 'bob', 'rock', 'jimy'], 'DoB': ['01/02/2010', '01/02/2012', '11/22/2014', '11/22/2014', '09/25/2016'], 'Address': ['NY', 'NJ', 'PA', 'NY', 'CA']}
df1 = pd.DataFrame(data = d)
df1['month'] = pd.DatetimeIndex(df['DoB']).month
df1['year'] = pd.DatetimeIndex(df['DoB']).year

这是示例表 2

d2 = {'row_num': [1, 2, 3, 4, 5], 'name': ['john', 'tom', 'bob', 'rock', 'jimy'], 'DoB': ['01/02/2010', '01/02/2012', '11/22/2014', '11/22/2014', '09/25/2016'], 'Address': ['NY', 'NJ', 'PA', 'NY', 'CA']}
df2 = pd.DataFrame(data = d)

表 2 或 df2 没有像 df1 那样的月份和年份列。我想找出 df2 中缺少 df1 的哪些列。

我知道 sql 中有“EXCEPT”,但是如何使用 pandas/python 来实现,有什么建议吗?

最佳答案

有一个函数就是为了这个目的:pd.Index.difference

df1.columns.difference(df2.columns)
Index(['month', 'year'], dtype='object')

以及,相应的列;

df1[df1.columns.difference(df2.columns)]

   month  year
0      1  2010
1      1  2012
2     11  2014
3     11  2014
4      9  2016

关于python - 如何使用Python根据列名找出两个数据框的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50335610/

相关文章:

python - 无法访问 Google AppEngine 外部库

python - Pandas 值错误 : Can only compare identically-labeled Series objects from single dataframe?

python - 在python脚本中使用youtube-dl仅从youtube视频下载音频

Python 内置堆 (heapq) : Odd behavior if inverted (max-heap)

python - 如何知道算法是否可以变得更快

python - 如何返回 numpy 数组的列主迭代器?

python - 通过键合并两个 Python 字典的值

python - 值错误: need more than one value to unpack

python - 如何创建新日期并作为索引插入 pandas 数据框中?

python - Pandas df 的流数据