【问题标题】:Comparing Column Values in a Pandas Dataframe比较 Pandas 数据框中的列值
【发布时间】:2017-03-08 22:00:10
【问题描述】:

我需要找出给定 Pandas 数据框中列值的不同之处。

我使用此处描述的技术组装了我的数据框:compare two pandas data frame

使用此代码,我可以获取新旧数据集之间添加的行和删除的行。其中 df1 是旧数据集,df2 是新数据集。它们具有相同的架构。

m = df1.merge(df2, on=['ID', 'Name'], how='outer', suffixes=['', '_'])
adds = m.loc[m.GPA_.notnull() & m.GPA.isnull()]
deletes = m.loc[m.GPA_.isnull() & m.GPA.notnull()]

我想要做的是从合并的数据框中过滤掉添加和删除,然后比较列值:

for col in m.columns:
    m["diff_%s" % field] = m[field] != m["%s_" % field]

这应该会导致添加多个用于检查值更改的布尔列。所以我的问题是,如何在应用此列逻辑之前先过滤掉添加和删除行?

附加信息:

_data_orig = [
[1, "Bob", 3.0],
[2, "Sam", 2.0],
[3, "Jane", 4.0]]
_columns = ["ID", "Name", "GPA"]

_data_new = [
        [1, "Bob", 3.2],
        [3, "Jane", 3.9],
        [4, "John", 1.2],
        [5, "Lisa", 2.2]
    ]
_columns = ["ID", "Name", "GPA"]

df1 = pd.DataFrame(data=_data_orig, columns=_columns)
df2 = pd.DataFrame(data=_data_new, columns=_columns)

m = df1.merge(df2, on=['ID', 'Name'], how='outer', suffixes=['', '_'])
adds = m.loc[m.GPA_.notnull() & m.GPA.isnull()]
deletes = m.loc[m.GPA_.isnull() & m.GPA.notnull()]

# TODO: add code to remove adds/deletes here
# array should now be: [[1, "Bob", 3.2],
#        [3, "Jane", 3.9]]
for col in m.columns:
    m["diff_%s" % field] = m[field] != m["%s_" % field]
# results in:
# array with columns ['ID', 'Name', 'GPA', 'Name_', 'GPA_','diff_GPD', 'diff_Name'
# ... DO other stuff
# write to csv

【问题讨论】:

  • 您可以从样本数据中添加所需的输出吗?
  • @jezrael 确定,现在更新。
  • @jezrael 代码已按要求更新

标签: python python-2.7 pandas indexing union


【解决方案1】:

您可以使用Index.union 将indexes 和drop 与idx 连接起来:

idx = adds.index.union(deletes.index)
print (idx)
Int64Index([1, 3, 4], dtype='int64')

print (m.drop(idx))
   ID  Name  GPA  GPA_
0   1   Bob  3.0   3.2
2   3  Jane  4.0   3.9

boolean indexing 的另一种解决方案:

mask = ~((m.GPA_.notnull() & m.GPA.isnull()) | ( m.GPA_.isnull() & m.GPA.notnull()))
print (mask)
0     True
1    False
2     True
3    False
4    False
dtype: bool

print (m[mask])
   ID  Name  GPA  GPA_
0   1   Bob  3.0   3.2
2   3  Jane  4.0   3.9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多