我想找出两个数据框之间在列名方面的区别。
这是示例表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这样的month和year列。我想找出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/